当我单击链接时,也会触发jQuery Table Row Click Event

问题描述

| 这是我到目前为止所拥有的,获取行号的效果很好,但是我需要这样做,以便当我单击表中的链接时,它不会触发函数内的代码
<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>
    

解决方法

        选择器.row:not(.link)将选择所有具有类\“ row \”而不具有类\“ link \”的元素,这不是您想要的。 您需要在a.link元素的click事件中使用event.stopPropagation,以便click事件不会传播到包括行在内的父项。 尝试这个:
<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>
    ,        有点晚了,但这是我在Google中打开的第一个链接,以寻找相关主题的解决方案。因此,它可能对某人有用:
$(\".clickableRow\").click(function(e) {
  if (e.target.nodeName != \"A\") {
    window.document.location = $(this).attr(\"href\");
  }
});
,        这是jQuery中的快速修复方法,只需使用instanceof
  $(\"#news-table tr\").click(function(e){
      if((e.srcElement instanceof HTMLAnchorElement)!=true  )console.log(\"IIIIIIHA HA!\");
  });
    ,        您需要防止事件在链接的click事件中传播-这是一个示例:http://jsfiddle.net/6t8u7/1/ 如您所见,单击链接只会触发一个事件。单击该行会引发其他事件。 您得到当前行为的原因是链接“冒泡”到父元素的click事件。     ,        有了data属性,就不需要一个类:
$(document).on(\'click\',\'[data-href]\',function(e) {
    if($(e.target).hasClass(\'ignore\'))
        return;
    var ignore = [\'input\',\'a\',\'button\',\'textarea\',\'label\'];
    var clicked = e.target.nodeName.toLowerCase();
    if($.inArray(clicked,ignore) > -1)
        return;
    window.location = $(this).data(\'href\');
});
用法示例(
tr
只是一个示例-您可以使用
div
等):
<tr data-href=\"your_url\">
    <td class=\"ignore\">Go nowhere</td>
    <td>Go to your_url</td>
    <td><a href=\"another_url\">Go to another_url</a></td>
    <td><input type=\"text\" value=\"Go nowhere\"></td>
</tr>
    ,        您也可以在不显式选择第二个功能中的行的情况下使用它。
$(function(){     
    $(\'.row\').click(function(){         
        var $row = $(this).index();     
    }); 
    $(\'.link\').click(function(event){
       event.preventDefault();
       event.stopPropagation();
    });
}); 
    ,        只需添加:将“ 9”添加到行单击,链接元素将使用其自己的逻辑。 这是更详细的示例:
$(\"#table tr\").click(function(e) {

    // Skip if clicked on <a> element
    if (e.target.tagName == \'A\') return;

    // Logic for tr click ...

});
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...