簡體   English   中英

在帶有點擊事件的li中,停止選中復選框兩次

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

我正在用jQuery寫一個簡單的下拉菜單,每個項目都有一個復選框。 當我單擊li元素時,該復選框已選中。 但是,如果我單擊復選框本身,則不會選中該復選框,因為它已被有效地選中了兩次。 我該如何阻止這種情況發生?

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:

$(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取消選中該復選框)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM