繁体   English   中英

jQuery取消选中子元素的复选框,然后选中该复选框

[英]jquery uncheck and check and vise versa checkbox of child element

这是我的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。

暂无
暂无

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

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