在带有点击事件的li中,停止复选框两次检查 [英] Stop checkbox being checked twice when inside an li with a click event

查看:179
本文介绍了在带有点击事件的li中,停止复选框两次检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery编写一个简单的下拉菜单,每个项目都有一个复选框。当我点击 li 元素时,将选中该复选框。但是,如果我单击复选框本身,它不会选择,因为它被有效地检查两次。如何阻止这种情况?

I'm writing a simple dropdown menu with jQuery and each item has a checkbox. When I click on an li element the checkbox is selected. However if I click on the checkbox itself, it does not select because it is effectively checked twice. How can I stop this happening?

jsFiddle: http:// jsfiddle.net/ZEp7V/

jsFiddle: http://jsfiddle.net/ZEp7V/

HTML

<div id="dropdown">Channels</div>
<ul class="droplist">
    <li>News <input type="checkbox" /></li>
    <li>Sport <input type="checkbox" /></li>
    <li>Science <input type="checkbox" /></li>
    <li>Health <input type="checkbox" /></li>
    <li>All</li>
</ul>

CSS:

div#dropdown {
    border: 1px solid #000;
    width: 150px;
    height: 20px;
    line-height: 20px;
    padding: 10px;
    cursor: pointer;
}

ul.droplist {
    display: none;
    width: 170px;
    border: 1px solid #000;
    border-bottom: none;
    list-style-type: none;
    padding: 0px;
    margin: 0px;
    position: absolute;
    background-color: #fff;
}

ul.droplist li {
    border-bottom: 1px solid #000;
    padding: 10px;
    cursor: pointer;
}

ul.droplist li input {
    float: right;
}

JS: b

$(document).ready(function(){

    $("#dropdown").click(function() {
        $(this).next().slideToggle(200);
    });

    $(".droplist li").click(function(e) {
        // Toggle the checkbox
        var input = $(this).children("input");
        $(input).prop("checked", !$(input).prop("checked"));
    });

    $(".droplist li:last").click(function () {
        // Select all boxes
        var check = $('.droplist li input:not(:checked)').length;
        $(".droplist li input").prop("checked", check);
    });

});


推荐答案

您可以停止复选框中事件的传播

$(".droplist li :checkbox").click(function (e) {
    e.stopPropagation();
});

这将阻止事件将DOM树冒泡到父 li 元素(其中,如你所说,它触发绑定到它的事件处理程序)。

This will prevent the event from bubbling up the DOM tree to the parent li element (where, as you say, it triggers the event handler bound to it).

作为附注,您可以修改代码以利用事件委派的优势,这更有效,因为每个 li 元素只有一个事件处理程序,而不是一个事件处理程序。例如:

As a side note, you could modify your code to take advantange of event delegation, which is more efficient since there's only one event handler instead of one for each li element. For example:

$(".droplist").on("click", "li", function (e) {
    // Toggle the checkbox
    var input = $(this).children("input");
    $(input).prop("checked", !$(input).prop("checked"));
});

查看 .on() 方法获取更多详细信息。

See the .on() method for more details.

这篇关于在带有点击事件的li中,停止复选框两次检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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