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