jQuery子元素选择器问题

4

I have the following code:

$("#Table1 tbody").children().each(function(e){
$(this).bind('click', 
            function(){
                // Do something here
            }, 
            false) 
});
名称

当我单击表格行时,它能够正常工作。但是当我单击按钮时,按钮代码会触发,表格行的代码也会同时触发。

如何过滤选择器,使得按钮不会触发父元素的点击事件?

3个回答

7

这是您想要的内容。

stopPropogation可以停止父级元素。

<table>
  <tr>
    <td>The TD: <input type="button" id="anotherThing" value="dothis"></td>
  </tr>
</table>

<div id="results">
  Results:
</div>

<script>

  $(function() {
    $('#anotherThing').click(function(event) {
       $('#results').append('button clicked<br>');
       event.stopPropagation();       
    });
    $('td').click(function() {
       $('#results').append('td clicked<br>');

    });
  });

</script>

这是一个示例链接:http://jsbin.com/uyuwi。您可以在http://jsbin.com/uyuwi/edit上进行调试。

2
您也可以像这样做:

$('#Table1 tr').bind('click', function(ev) {
  return rowClick($(this), ev);
}); //Bind the tr click
$('#Table1 input').bind('click', function(ev) {
  return buttonClick($(this), ev);
}) //Bind the button clicks

function rowClick(item, ev) {
  alert(item.attr('id'));
  return true;
}

function buttonClick(item, ev) {
  alert(item.attr('id'));
  ev.stopPropagation();

  return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Table1">
  <tbody>
    <tr id="tr1">
      <td>
        The TD: <input type="button" id="button1" value="dothis" />
      </td>
    </tr>
    <tr id="tr2">
      <td>
        The TD: <input type="button" id="Button2" value="dothis" />
      </td>
    </tr>
  </tbody>
</table>


0

能不能删除按钮代码,只运行行代码,从而使用事件冒泡呢?

另外还有几个选项:

  • 你可以给包含按钮的 TD 添加一个类,并在选择器中执行 '[class!="className"]'
  • 也许尝试使用 event.preventDefault()。您可以在这里看到它的使用方式。这样,您就可以防止在单击按钮时触发默认操作,虽然我不确定它是否完全阻止了冒泡。

最终,点击行是选择操作,而按钮的onclick是删除操作。我还没有找到一个好的方法来使这些工作。 - JamesEggers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接