jquery - 重叠 onClick() 事件表内的元素
问题描述
<td>
我在HTML 表格的标签内创建了一个按钮。
我添加了一个监听器来触发点击事件的警报。
HTML 表格的<td>
标签对事件侦听器同样紧密,并在单击时触发带有与按钮不同的文本的警报。
下面的代码片段说明了上面的场景。
$("#mytable").on("click", "td", function() {
alert('this is td');
});
$("#mybutton").on("click", function() {
alert('this is button');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="mytable">
<tr>
<td style="border: 1px solid black; width: 500px; height: 20px">
<span>table</span>
<button style="margin: 5px; padding:5px; border: 1px solid black; float: right" id="mybutton"> display</button>
</td>
</tr>
</table>
如何在不触发包含按钮的<td>
标签的单击事件的情况下有效地执行按钮上的单击事件?
解决方案
在单击您的按钮后,您必须停止单击事件的传播。这是通过对事件调用stopPropagation()函数来完成的。否则 - 正如您所经历的那样 - 事件将传播到下一个元素。
这是一个例子:
$("#mytable").on("click", "td", function() {
alert('this is td');
});
$("#mybutton").on("click", function(event) {
event.stopPropagation();
alert('this is button');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="mytable">
<tr>
<td style="border: 1px solid black; width: 500px; height: 20px">test
<button style="margin: 5px; padding:5px; border: 1px solid black; float: right" id="mybutton"> display</button>
</td>
</tr>
</table>
推荐阅读
- vue.js - 模块解析失败:意外字符 '' (1:2) 您可能需要适当的加载程序来处理此文件类型
- python - 我正在尝试将 bibles.print("Gen", 1, 1) 输出保存到文本文件中。我该怎么做呢?
- width - 如何绘制线宽大于 1 像素的形状(椭圆、矩形、圆形等)
- python - 如何用乌龟创建一排星星
- python-3.x - 根据条件替换python numpy矩阵值,而不使用for循环
- python - 位置和关键字标记 / * 语法错误
- html - 如何隐藏移动媒体查询上的按钮并在点击时显示它们?
- python - 尝试将用户输入的输出显示到同一个 html 屏幕上
- flutter - 可以在 Flutter 中识别文本小部件中字符的全局位置
- azure - Azure AD B2C,我们能否以编程方式将用户从应用程序注册/登录到应用程序内的天蓝色广告?