JQuery 不会 select 并更改复选框的状态

JQuery doesn't select and change the state of a checkbox

这是html:

<div class="btn btn-stock-report" id="superman">
    Superman <input type="checkbox" name="superman" />
</div>

这是 JQuery:

$('#superman').on('click', function () {
    if ($(this).children('input:checkbox:first').is(':checked')) {
        superman = true;
        $(this).children('input:checkbox:first').removeAttr('checked');
    }
    else {
        superman = false;
        $(this).children('input:checkbox:first').attr('checked', 'checked');
    }
    console.log("superman: " + superman);
});

我想要实现的只是更改子复选框的状态并更改 superman 变量的值,但由于某种原因它总是在控制台中打印出 superman: false日志。即使我手动选中复选框并单击 div,即使现在选中了复选框,它也会报告 superman: false

可能是什么原因造成的?

可以 只需将 <div> 更改为 <label> 并删除所有 jQuery 代码,它就会正常工作。

您应该使用 .prop() 而不是 attr,因为 checked 是复选框的 属性。您也可以将代码范围缩小到:

$('#superman').on('click', function () {
 var chk = $(this).find('input:checkbox:first')
 chk.prop("checked", !chk.prop("checked"));
});

Working Demo

$('#superman').on('click', function () {
    superman = !$(this).children('input:checkbox:first').is(':checked');
    $(this).children('input:checkbox:first').prop('checked',superman);
    console.log("superman: " + superman);
});