How to handle a click on a but not on the chi

2019-06-24 08:15发布

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?

3条回答
家丑人穷心不美
2楼-- · 2019-06-24 08:41

You can check event.target to filter your events:

$('table tr').click(function(e){
    if(e.target.tagName.toLowerCase() != "input") {
        alert('clicked');
    }
});​
查看更多
3楼-- · 2019-06-24 08:42

You could also use

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

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

});
查看更多
唯我独甜
4楼-- · 2019-06-24 08:47

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();
});
​
查看更多
登录 后发表回答