【问题标题】:How can I click a checkbox and know if checked or not checked? [duplicate]如何单击复选框并知道是否选中? [复制]
【发布时间】:2018-11-23 15:16:39
【问题描述】:

$('.p_check').click(function() {
          if ($(this).is(':checked')) {
              alert("checked");
          } else {
               alert("unchecked");
          }
       });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='checkbox p_check'><label><input type='checkbox'>New Password</label></div>

我的警报总是“未选中”,无论我是选中还是取消选中它

【问题讨论】:

  • $('.p_check')&lt;div&gt;。你为什么希望它被检查?
  • 另外,一旦你修复了不正确的选择器,你就不必做$(this).is(':checked') 只需使用this.checked 并避免使用 jQuery 来访问该属性

标签: jquery checkbox checked unchecked


【解决方案1】:

您正在使用 div 作为元素进行检查,但您应该使用复选框:

$('.p_check').click(function() {
var cb =    $(this).find('input[type="checkbox"]');
          if (cb.is(':checked')) {
              alert("checked");
          } else {
               alert("unchecked");
          }
       });

【讨论】:

  • 或者改为选择复选框?而不是为绑定修复不正确的选择器?
  • 是的,我把类放错了元素,我的错
猜你喜欢
  • 2015-06-21
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 2012-10-22
  • 2016-10-07
  • 2014-10-12
相关资源
最近更新 更多