javascript - jQuery 只工作一次? jsFiddle 已附

标签 javascript jquery

我希望能够通过单击其父 DIV 来选中和取消选中复选框。

html:

<div class="insurance-option-select">
    <input name="insurance[Auto]" type="checkbox" value="1">
</div>
<div class="insurance-option-select">
    <input name="insurance[Home]" type="checkbox" value="2">
</div>

js:

  $('.insurance-option-select').on('click', function () {
      if ($(this).find('input').prop('checked')) {
          $(this).find('input').removeAttr('checked');
      } else {
          $(this).find('input').attr('checked', true);
      }
  });

CSS:

.insurance-option-select {
    background: red;
    padding: 30px;
    margin: 30px auto;
}
.insurance-option-select:hover {
    background: green;
}

问题是它只能工作一次。 http://jsfiddle.net/zbh691y0/

最佳答案

始终使用 prop,而不是 attr 和 prop。

http://jsfiddle.net/zbh691y0/1/

$('.insurance-option-select').on('click', function () {
    if ($(this).find('input').prop('checked')) {
        $(this).find('input').prop('checked', false);
    } else {
        $(this).find('input').prop('checked', true);
    }
});

这也可以通过执行以下操作来简化:

$('.insurance-option-select').on('click', function () {
    cb = $(this).find('input')
    cb.prop('checked', ! cb.prop('checked'))
});

属性checked是一个 bool 值。因此,您可以使用 ! 来否定它的值。想象一下这段代码:

   cb = $(this).find('input') 
   is_checked = cb.prop('checked')  // This will be true if it is checked, and false if not
   inverse_is_checked = ! is_checked // This will be the opposite of is_checked
   cb.prop('checked', inverse_is_checked) // Now you set the checked property value to the inverse of what it was originally

但这可以在一行中完成,如上所示。

关于javascript - jQuery 只工作一次? jsFiddle 已附,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755332/

相关文章:

jquery - SVG 矩形的单击事件

jquery - datePicker 出现在页面加载时

javascript - 如何使用angular js上下移动项目?

c# - 你如何对抗所有这些方式? -Javascript 及其数百万种不同的编写方式

javascript - 如何在 jQuery ajax 请求中获取 HTML 网页的一部分?换句话说,如何在 ajax 调用中过滤网页内容?

javascript - 如何更改 flashvarsObj

javascript - 如何使文本框显示一个值,但单击时显示另一个值?

javascript - 处理可能异步的动态脚本

jquery - 我在使用 jQuery 加载和解析 XML 时遇到问题,我做错了什么?

javascript - 在浏览器底部将 div 从 fixed 切换为 absolute