How to handle a click on a <tr> but not on the child elements?

风格不统一 提交于 2019-12-23 13:54:43

问题


I handling the click with following code.

Table with input

<table>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
    </tr>
</table>​

Click handler

$('table tr').click(function(){
    alert('clicked');
});​

http://jsfiddle.net/n96eW/

It's working well, but if I have a checkbox in the td, it's handling it too when clicked.

Is there a way to handle the click of the TR but not trigger on the child elements?


回答1:


http://jsfiddle.net/n96eW/1/

Add another event handler in your checkbox to stopPropagation:

$('table tr').click(function(){
    alert('clicked');
});

$('table tr input').click(function(e) {
    e.stopPropagation();
});
​



回答2:


You can check event.target to filter your events:

$('table tr').click(function(e){
    if(e.target.tagName.toLowerCase() != "input") {
        alert('clicked');
    }
});​



回答3:


You could also use

$("tr").on('click',function() {

  if (!$(event.target).is('input'))
    alert('clicked');

});


来源:https://stackoverflow.com/questions/10086671/how-to-handle-a-click-on-a-tr-but-not-on-the-child-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!