我正在编写一些 javascript (jQuery),使 div 包裹在复选框周围,单击时将切换复选框元素。但是,我遇到的问题是,当您单击复选框时,它不起作用,因为它被切换了两次(至少我认为这是正在发生的事情)。
代码如下:
$('.checkbox-wrapper').click(function(){
var $checkbox = $(this).find('input[type="checkbox"]');
if ($checkbox.is(':checked')) {
$checkbox.attr('checked', false);
} else {
$checkbox.attr('checked', true);
}
});
我怎样才能让点击复选框正常工作,但如果你点击周围区域,它会切换复选框?
解决方案:
感谢 jAndy 的评论,展示了如何通过检查 event.target 属性来完成此操作:
$('.checkbox-wrapper').click(function(e){
if( e.target.nodeName === 'INPUT' ) {
e.stopPropagation();
return;
}
var $checkbox = $(this).find('input[type="checkbox"]');
if ($checkbox.is(':checked')) {
$checkbox.attr('checked', false);
} else {
$checkbox.attr('checked', true);
}
});
正如其他人所指出的,这可能不是最好的例子,因为您通过使用 label 标签而不是 div 标签包装复选框来获得相同的功能(不需要 javascript)。 Demo
最佳答案
检查 event.target
属性(property)。
The
target
property can be the element that registered for the event or a descendant of it. It is often useful to compareevent.target
tothis
in order to determine if the event is being handled due to event bubbling.
关于Javascript:单击包装元素而不是子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930640/