jQuery取消选中并选中子元素的反之亦然复选框

jquery uncheck and check and vise versa checkbox of child element

本文关键字:反之亦然 复选框 元素 取消 jQuery      更新时间:2023-09-26

这是我的html

#This will be generated throught loop
<li class="selector">
    <a>
    <input type="checkbox" value="test" /> test
    </a>
</li>

这是我的jquery点击事件

$('.selector').on('click', function() {
    if($(this).find('input').is(':checked')){
    #uncheck the checkbox       
    }else{
    #check the checkbox
    }
});
如果选中则

取消选中,如果未选中,则如何检查

尝试

$(document).on('click', '.selector', function (e) {
    if (!$(e.target).is('input')) {
        $(this).find('input').prop('checked', function () {
            return !this.checked;
        });
    }
});

演示:小提琴

另一种方式

$(document).on('click', '.selector', function (e) {
    $(this).find('input').prop('checked', function () {
        return !this.checked;
    });
});
$(document).on('click', '.selector input', function (e) {
    e.stopPropagation();
});

演示:小提琴

试试这个

$('.selector').on('click', function() {
        var checkbox = $(this).find(':checkbox');
        if($(checkbox).is(':checked')){
             $(checkbox).prop('checked', false);     
        }else{
        #check the checkbox
             $(checkbox).prop('checked', true);
        }
    });
我不

明白你为什么要用JavaScript来做这件事。如果用户直接单击复选框,它将自动检查/取消选中自己,但是如果您在 JS 中添加代码来选中/取消选中它,这将取消默认行为,因此在您的单击处理程序中,您需要测试单击是否在.selector中的其他地方。

Anwyay,.prop()方法可以满足您的需求:

$('.selector').on('click', function(e) {
    if (e.target.type === "checkbox") return; // do nothing if checkbox clicked directly
    $(this).find("input[type=checkbox]").prop("checked", function(i,v) {
        return !v; // set to opposite of current value
    });
});

演示:http://jsfiddle.net/N4crP/1/

但是,如果您的目标只是允许单击文本"test"以单击该框,则不需要JavaScript,因为这是<label>元素的作用:

<li class="selector">
    <label>
    <input type="checkbox" value="test" /> test
    </label>
</li>

正如你在这个演示中看到的:http://jsfiddle.net/N4crP/2/- 点击文本"test"或复选框将切换当前值,没有任何JavaScript。