简体   繁体   English

jQuery复选框

[英]Jquery check checkbox

I have a parent div which hold a check box what i would like to achieve is check or uncheck the wherever I click in the parent div or directly on the check box. 我有一个父div,其中包含一个复选框,我想实现的是选中或取消选中我在父div中单击的位置或直接在复选框上单击的位置。

$('.select').click(function(){
    var checkbox = $(this).find('input[type=checkbox]')
    if (checkbox.is(':checked')){
        checkbox.prop('checked', false);
    }else{
        checkbox.prop('checked', true);
    }
});

http://jsfiddle.net/halirgb/Lt2Hw/2/ http://jsfiddle.net/halirgb/Lt2Hw/2/

The problem is that if you click directly on the check box it dos not check :( 问题是,如果直接单击复选框,则不检查:(

Can anyone help? 有人可以帮忙吗?

It is because event propagation. 这是因为事件传播。

When you click on the checkbox first the checkbox changes its state, then the event is propagated to the the parent elements thus reaching the .select element where the state is again reversed to so it gets back to the state before the click 当您首先单击该复选框时,该复选框会更改其状态,然后该事件将传播到父元素,从而到达.select元素,状态再次反转为该状态,因此它会回到单击之前的状态

Try 尝试

$('.select').click(function (e) {
    var checkbox = $(this).find('input[type=checkbox]')
    if (checkbox.is(e.target)) {
        return;
    }

    checkbox.prop('checked', function (i, checked) {
        return !checked;
    });
});

Demo: Fiddle 演示: 小提琴


Or prevent the propagation of the click event from the checkbox 或阻止单击事件从复选框传播

$('.select').click(function (e) {
    var checkbox = $(this).find('input[type=checkbox]')
    checkbox.prop('checked', function (i, checked) {
        return !checked;
    });
});
$('.select input[type=checkbox]').click(function (e) {
    e.stopPropagation();
});

Demo: Fiddle 演示: 小提琴

Demo Fiddle 演示小提琴

Use event.stoppropagation 使用event.stoppropagation

Stop Propagation on Checkbox click event. 在复选框单击事件中停止传播。

$('.select input[type=checkbox]').click(function (e) {
    e.stopPropagation();
});


Problem 问题

When you click on checkbox the parent is also clicked so event fires when changes it's state again . 当您单击复选框时,也会单击父级,因此事件再次更改其状态时会触发。

Check this demo to understand the problem 查看此演示以了解问题

Demo Fiddle 演示小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM