我试图允许单击包含复选框的div,以使该复选框被选中 . 只要选中该复选框,其父div就会改变颜色 . 未选中时,父div的背景颜色将恢复为原始颜色 .
Problem: 单击复选框's div is correct. However, when clicking on the checkbox directly, the behavior is opposite of what is desired. I suspect this is due to double clicking: The checkbox'自己的单击处理程序时的行为,以及其父div的单击处理程序 . 我可能在这里错了 . 我该如何解决?
JS
// Click checkbox when its container is clicked
$(".organizer_listing_checkbox_container_container").click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function() {
if($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
} else {
$(this).parent().parent().parent().css('background-color', "#FFF");
}
});
HTML
<div class="organizer_listing">
<div class="organizer_listing_checkbox_container_container">
<div class="organizer_listing_checkbox_container" data-listing_id=1234>
<input type="checkbox" class="organizer_listing_checkbox" />
</div>
</div>
</div>
EDIT: Swapped the background colors + e.stopPropagation()
// Click checkbox when its container is clicked
$(".organizer_listing_checkbox_container_container").click(function(event) {
$(':checkbox', this).trigger('click');
});
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function(e) {
e.stopPropagation();
if($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
} else {
$(this).parent().parent().parent().css('background-color', "#FFF");
}
});
4 回答
使用on()绑定事件(jQuery 1.7) . 以下方法将:
在复选框更改时切换颜色(使用
change
而不是click
以允许键盘启动的状态更改) .点击
<div>
切换检查状态演示:http://jsfiddle.net/sPb9f/1/
您可能想尝试使用
label
然后在复选框上使用change
处理程序 . 单击与复选框关联的标签在功能上与单击复选框相同 . 通过使用change
处理程序,您可以处理复选框值更改的所有事件 .我有点疯狂并重写了大部分代码(demo):
你必须停止传播: