.is( ":checked" ) 在 jQuery 中不起作用



我是jQuery的新手,我需要检查是否检查了复选框。在其他帖子中,我看到我需要使用.is(":checked")来解决它,但是它不起作用。

$('.neutral').on('click', function() {
  var checkbox = $(this);
  if (checkbox.is(":checked")) {
    console.log('checked');
  } else {
    console.log('unchecked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />

在此代码中,我有2个问题,我不知道如何解决。

  1. 当我在if语句之外使用console.log('checked')checkbox变量之后)时,我一次单击复选框时,控制台将2次打印结果。

  2. 我不知道为什么如果语句不起作用。

感谢您的时间和帮助。

检查发生后发生的检查,只需更换单击。

$('.neutral').on('change', function() {
  var checkbox = $(this);
  if (checkbox.is(":checked")) {
    console.log('checked');
  } else {
    console.log('unchecked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />

我看过您的代码,我认为您应该尝试

$(document).on("click",".neutral",function() {
        // Write code here
    });

而不是您的代码,将此代码替换为我写的

$('.neutral').on('click', function() {
     // Code here
});

有关更多不希望的信息,请参见此处

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });
    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });
    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
}); 

访问这些链接,可能会帮助您更多地实施

statck flow链接

jsfiddle链接

最新更新