2012-07-04 30 views
1

我正在用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); 
    }); 

}); 

回答

7

您可以在複選框事件的stop the propagation

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

這將防止事件的DOM樹冒泡到父li元素(其中,如你所說,它觸發事件處理程序綁定到它)。


作爲一個側面說明,你可以修改你的代碼,以事件的代表團,這是更有效,因爲只有一個事件處理程序,而不是爲每個li元素的advantange。例如:

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

有關更多詳細信息,請參閱.on()方法。

1

裹複選框用標籤(標籤共享與輸入瀏覽器的本地click事件)

<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取消選中它)

相關問題