[英]Checkbox functionality not working when parent has a click event
I have a checkbox inside a div which has a click event attached to it. 我在div内有一个复选框,其中附加了click事件。 But the checking and unchecking the checkbox directly doesn't work. 但是直接选中和取消选中复选框不起作用。
<div class="container" onclick="select(this)">
<input type="checkbox" value="" /><label>Item</label>
</div>
function select(e) {
var elm = $(e);
var chkBox = elm.find('input');
console.log(chkBox.is(':checked'));
if(chkBox.is(':checked')) {
chkBox.prop("checked", false);
}else{
chkBox.prop("checked", true);
}
}
Demo : http://jsfiddle.net/h45A5/ 演示: http : //jsfiddle.net/h45A5/
You should write var elm = getElementById('e');
您应该写var elm = getElementById('e');
instead of var elm = $(e);
而不是var elm = $(e);
Try it yourself: http://jsfiddle.net/h45A5/3/ 自己尝试: http : //jsfiddle.net/h45A5/3/
Try to bind event properly rather than using an inline handler, 尝试正确地绑定事件,而不是使用内联处理程序,
HTML: HTML:
<div class="container">
<input type="checkbox" value="" /><label>Item</label>
</div>
JS: JS:
$('div.container').click(function(e){
if($(e.target).is(':checkbox')){ return; }
var chkBox = $(this).find(':checkbox');
chkBox.prop("checked", !chkBox.is(':checked'));
});
If I understand correctly, you want the checkbox to toggle if either the div
and the checkbox
are clicked, in which case, add 如果我理解正确,则希望单击div
和复选框时切换checkbox
,在这种情况下,请添加
$('input[type="checkbox"]').click(function(e){
e.stopPropagation();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.