jQuery单击停止传播 [英] jQuery Click Stop Propagation

查看:82
本文介绍了jQuery单击停止传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的设置,一个表格,其中的单元格内有复选框.我有两个事件,一个事件响应单击复选框,另一个事件响应单击"tr"元素.当我单击复选框时,我不希望触发表行事件.我试过event.stopPropagation()return false;时没有任何运气.这是一个片段:

I have a simple setup, a table whose cells have checkboxes within them. I have two events, one that responds to clicking on the checkboxes and another which responds to clicking on the "tr" elements. When I click on a checkbox I don't want the table row event to fire. I've tried event.stopPropagation() and return false; without any luck. Here's a snippet:

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

$("input[type=checkbox]").change(function(event) {
    event.stopPropagation();
    alert("checkbox clicked");
});

类似:

<tr>
    <td><input type="checkbox" id="something" name="something" /></td>
</tr>

如果更改事件触发,则单击事件也会触发.如果复选框在trtd元素内被更改,则如何阻止触发tr click事件的任何线索?

If the change event fires the click event will also fire. Any clues on how to stop the tr click event from firing if the checkbox is changed within the td element of the tr?

推荐答案

我建议这样做:

$( '#theTable' ).delegate( 'tr', 'click', function ( e ) {
    if ( $( e.target ).is( 'input:checkbox' ) ) { 
        alert( 'checkbox clicked' );
    } else {
        alert( 'tr clicked' );
    }        
});

因此,整个表只有点击处理程序.

So, you have only one click handler for the entire table.

顺便说一句,您不必将所有代码都放在该处理程序中.您可以为每个操作设置单独的功能(单击复选框,单击VS行),然后...

Btw, you don't have to place all the code inside this one handler. You can have separate functions for each action (checkbox clicked VS row clicked), and then...

$( '#theTable' ).delegate( 'tr', 'click', function ( e ) {
    if ( $( e.target ).is( 'input:checkbox' ) ) { 
        checkboxClicked( e );
    } else {
        rowClicked( e );
    }        
});

function checkboxClicked ( e ) {
    // process event
}

function rowClicked ( e ) {
    // process event
}

这篇关于jQuery单击停止传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆