首页 > 解决方案 > 重叠 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>标签的单击事件的情况下有效地执行按钮上的单击事件?

标签: jquery

解决方案


在单击您的按钮后,您必须停止单击事件的传播。这是通过对事件调用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>


推荐阅读