search

Home  >  Q&A  >  body text

javascript - 点击文字勾选checkbox,第一次生效,第二次就不灵了

<p class="e_checkbox">
    <input type="checkbox">
    <span>选项一</span>
</p>

$('.e_checkbox span').click(function(){

var eInputCheckbox = $(this).parent().find('input');
if(eInputCheckbox.is(':checked')){
    eInputCheckbox.attr("checked", false);
    console.log(eInputCheckbox.attr("checked"));
}else{
    eInputCheckbox.attr("checked", true);
    console.log(eInputCheckbox.attr("checked"));
}

});

阿神阿神2902 days ago170

reply all(5)I'll reply

  • 黄舟

    黄舟2017-04-10 17:25:48

    attr 改成prop

    jQuery 建议:To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

    特意写了一篇文章《jQuery 的 attr 与 prop 的区别》

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 17:25:48

    试了下, 没看出 问题。。。
    lz 的问题 是什么不灵了?

    reply
    0
  • 黄舟

    黄舟2017-04-10 17:25:48

    不知道find(“input")是不是个数组,后面放[0] ?

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 17:25:48

    不应该是set true/false ,而是removeAttr('checked') , input 的checked属性类型是bool,而不是说他的值是bool,只要这个属性存在,不管他的值是什么都表示checked状态。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 17:25:48

    $('.e_checkbox span').click(function(){

         var eInputCheckbox = $(this).parent().find('input');
           if(eInputCheckbox.is(':checked')){
              eInputCheckbox.prop("checked", false);
              console.log(eInputCheckbox.attr("checked"));
           }else{
             eInputCheckbox.prop("checked", true);
             console.log(eInputCheckbox.attr("checked"));
           }
     });

    reply
    0
  • Cancelreply