2011-01-28 118 views
0

冒泡我有一个简单的HTML表格看起来像这样处理事件的jQuery中

<table id='resultGrid'> 
    <tr> 
     <td> 
     <a href='javascript:callAction(xxx)'>Johnny</a> 
     </td> 
     <td> 
     Active 
     </td> 
    </tr> 
    <tr> 
     <td> 
     <a href='javascript:callAction(yyy)'>Nitro</a> 
     </td> 
     <td> 
     In Active 
     </td> 
    </tr> 
</table> 

,我想同时处理排CLIK和hypherlink点击。由于希弗链接已经连接到callAction()函数,我用jQuery来click事件添加到该行

$("#resultGrid tr").each(function(){ 
     $(this).css('cursor','hand'); 
     $(this).click(function() { 
      //My logic 
     }); 
}); 

现在的问题是,每次我单击超链接,该行单击事件也触发。我如何防止这一点。

+0

因为超链接是tablerow的内部,tablerows回调将首先触发,因为它是锚的父元素。 – diceler 2011-01-28 09:03:42

+0

@Ziga,我明白,...什么是避免这种方式.... – RameshVel 2011-01-28 09:09:47

回答

3

你可以使用e.target.nodeName

$("#resultGrid tr").each(function() { 
    $(this).css('cursor', 'hand'); 
    $(this).click(function(e) { 
     alert(e.target.nodeName.toLowerCase() != 'a'); 
    }); 
}); 

demo

1

您可以防止事件通过

e.stopPropagation() 

你也可以使用CSS指定样式您tr元素bubling。

$("#resultGrid a").click(function(e){ 
    // do your code 
    e.stopPropagation(); // prevent event bubbling 
}); 
+0

谢谢Rahul,它的工作.. :) – RameshVel 2011-01-28 09:11:43