is(':checked')/this.checked 不工作

is(':checked')/this.checked not working

发帖前尝试了几种解决方案,但 none 似乎有效,我一定是做错了什么。

我的代码如下(简化)

<label>
    <input type="checkbox" id="menu-image-settings-container" value="1" name="..." checked="checked">
    Add image?
</label>

<div class="image-settings">show content if checked</div>

js代码

$( ".image-settings" ).hide();

var wrapper = $(this).closest('li.menu-item');      

if ( $('input#menu-image-settings-container').is(':checked') ) {
    wrapper.find('.image-settings').show();
    console.log('is-checked');
} else {
    wrapper.find('.image-settings').hide();
    console.log('is-not-checked');
}


$('input#menu-image-settings-container').change(function(){
    if(this.checked) {
        wrapper.find('.image-settings').show();
    } else {
        wrapper.find('.image-settings').hide();
    }
}); 

console.log 表示 is-not-checked,而它显然在源代码中。 我试过使用 if ($('input#menu-image-settings-container').is(':checked')) {...} 但这也没有用,虽然通常它也应该有效。

首先,is(':checked') 是一个正确的解决方案。原因如下: 您可以看到,在这部分代码中,您的 console.log 有效。

实际问题出在这个结构中:wrapper.find('.image-settings').hide();这段代码找不到你的 .image-settings 元素。

我已将其替换为 $('.image-settings') 只是为了告诉您问题出在这里。

$('input#menu-image-settings-container').change(function() {
    if($(this).is(':checked')) {
        $('.image-settings').show();
    } else {
        $('.image-settings').hide();
    }
}); 

调试代码时,最好始终逐行使用 console.log。然后你就会清楚的看到你到底哪里出了问题