在具有单击事件的 li 内时停止选中两次复选框

Stop checkbox being checked twice when inside an li with a click event

本文关键字:复选框 两次 单击 事件 li      更新时间:2023-09-26

我正在用jQuery编写一个简单的下拉菜单,每个项目都有一个复选框。 当我单击li元素时,复选框处于选中状态。 但是,如果我单击复选框本身,它不会选择,因为它被有效地选中了两次。 我怎样才能阻止这种情况的发生?

js小提琴: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:

$(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元素(正如您所说,它触发绑定到它的事件处理程序)。


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

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

有关更多详细信息,请参阅 .on() 方法。

用标签包装复选框(标签与输入共享浏览器原生点击事件)

<li><label for="news_input">News <input type="checkbox" id="news_input" /></label></li>
<li><label for="sport_input">Sport <input type="checkbox" id="sport_input" /></li>
<li><label for="science_input">Science <input type="checkbox" id="science_input" /></li>
<li><label for="health_input">Health <input type="checkbox" id="health_input" /></li>

并摆脱这种行为

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

像这样,你应该没事。您的解决方案的问题在于,一旦用户单击输入,本机浏览器复选框函数和 jQuery 就会相互终止。(浏览器勾选复选框,jQuery取消选中)