繁体   English   中英

在jQuery事件处理程序中检查input [type = checkbox]

[英]Check input[type=checkbox] in jQuery event handler

我有以下HTML:

<ul id=list>
    <li>
        <input type=checkbox />
        Item 1
    </li>
    <li>
        <input type=checkbox />
        Item 2
    </li>
    <li>
        <input type=checkbox />
        Item 3
    </li>
</ul>

以及相应的Javascript:

$('ul').bind('click', function(e) {

    if (e.srcElement.tagName.toLowerCase() === 'input') {
        e.srcElement.checked = true;
    }

    return false;
});

$('body').bind('click', function() {

    alert('you should see this alert if and only if you did NOT click the list');

})

当我单击一个复选框时,它不会被选中。 我希望在用户单击它时对其进行检查。

我如何做到这一点,以便在用户单击复选框时将其选中,但仍取消body单击事件处理程序?

我也写了一个JS小提琴

编辑:我知道代码有点笨拙,但是对于应用程序,它需要以这种方式进行结构化,因此解决方案应尽可能接近原始代码。 话虽如此,对所观察到的行为的解释将是可理解的。

使用e.stopPropagation() [docs]而不是return false 后者还可以防止发生默认操作,即切换复选框的状态。

您还应该考虑将事件处理程序绑定到change事件,而不是click ,这不是切换复选框的唯一方法。 不过,您仍然需要添加其他处理程序以防止click事件冒泡。

  1. 您要将click绑定到“ ul”,应将其绑定到“ ul> input”
  2. 为了避免单击冒泡,您需要使用event.stopPropagation()取消冒泡,我注意到stopPropagation()应该是函数中的第一件事。

     $('ul').bind('click', function(e){ e.stopPropagation(); if (e.target.tagName.toLowerCase() === 'input') { e.target.checked = true; } }); $('body').bind('click', function() { alert('you should see this alert if and only if you did NOT click the list'); }); 

我想就是你想要的吗?

$('ul').bind('click', function(e) {          
    e.stopPropagation();       
});

$('body').bind('click', function() {
    alert('you only see this alert if and only if you did NOT click the list');
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM