jQuery表行单击一个链接时单击事件也会触发

Bra*_*don 11 html javascript jquery

这是我到目前为止,得到行号工作得很好,但我需要这样做,以便当我点击表中的链接时,它不会触发函数内的代码.

<table>
  <tr class="row">
    <td>A</td>
    <td><a class="link" href="foo.html">Foo</a></td>
  </tr>
  <tr class="row">
    <td>B</td>
    <td><a class="link" href="Bar.html">Bar</a></td>
  </tr>
</table>


<script>
$(function(){
    $('.row:not(.link)').click(function(){
        var $row = $(this).index();
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

Cha*_*ndu 42

选择器.row:not(.link)将选择所有具有"row"类且没有"link"类的元素,这不是您要查找的内容.

您需要在a.link元素的click事件中使用event.stopPropagation,以便click事件不会传播到包含row的父项.

试试这个:

<table>
    <tr class="row">
        <td>A</td>
        <td><a class="link" href="foo.html">Foo</a></td>
    </tr>
    <tr class="row">
        <td>B</td>
        <td><a class="link" href="Bar.html">Bar</a></td>
    </tr>
</table>

<script> 
    $(function(){     
        $('.row').click(function(){         
            var $row = $(this).index();     
        }); 
        $('.row .link').click(function(e){
            e.stopPropagation(); 
        });
    }); 
</script>
Run Code Online (Sandbox Code Playgroud)

  • @Nathan:我从未提到选择器不起作用(而选择器不是问题).我试图强调那个选择器不是必需的而且实际上:not(.link)在这个上下文中是无用的. (3认同)

Jac*_*dek 5

这是 jquery 中的快速修复,只需使用 instanceof

  $("#news-table tr").click(function(e){
      if((e.srcElement instanceof HTMLAnchorElement)!=true  )console.log("IIIIIIHA HA!");
  });
Run Code Online (Sandbox Code Playgroud)


erm*_*hko 5

有点晚了,但这是我在Google中打开的第一个链接,以寻找相关主题的解决方案。因此,它可能对某人有用:

$(".clickableRow").click(function(e) {
  if (e.target.nodeName != "A") {
    window.document.location = $(this).attr("href");
  }
});
Run Code Online (Sandbox Code Playgroud)

连续的链接,我的意思是standart,将照常工作,此示例标记将具有三个独立的链接激活:

<tr class="clickablerow" href="profile.html">

  <td>John Doe, the VP</td>
  <td><a href="print.html" target="_blank">Print</a><a href="chat.html" target="_blank">Chat</a></td>
    
</tr>
Run Code Online (Sandbox Code Playgroud)