鍍金池/ 問答/HTML5  網(wǎng)絡(luò)安全  HTML/ 不能理解的checkbox選中??

不能理解的checkbox選中??

  • 想實(shí)現(xiàn)的最終效果:點(diǎn)擊某個(gè)復(fù)選框,取消其它選中狀態(tài),只選中當(dāng)前選框

圖片描述

  • 實(shí)現(xiàn)代碼:
<body>
  <input type="checkbox"> 復(fù)選框1
  <input type="checkbox"> 復(fù)選框2
  <input type="checkbox"> 復(fù)選框3
  <input type="checkbox"> 復(fù)選框4
  <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <script type="text/javascript">
    $('input:even').attr('checked', true);
    $('input').click(function(){
      $('input').attr('checked', false);
      // $(this).attr('checked', true);
      this.checked = true;
    })
  </script>
</body>
  • 對上述代碼提的幾個(gè)問題:

1、點(diǎn)擊后重置所有選框?yàn)槲催x中

$('input').attr('checked', false);

而只選中當(dāng)前選框

// 原生js實(shí)現(xiàn)
this.checked = true;

可問題就出在這里,直選中當(dāng)前選框的代碼為什么不能這樣寫:

// jQuery實(shí)現(xiàn)
$(this).attr('checked', true);

2、如果設(shè)置為jQuery方式實(shí)現(xiàn)當(dāng)前選中,明明已經(jīng)設(shè)置了(看F12),可就是沒效果

圖片描述

回答
編輯回答
雅痞
$('input').attr('checked', false);

換成

$('input').prop('checked', false);

即可

checked屬性實(shí)際上對應(yīng)的是defaultChecked特性,設(shè)定多選框的初始狀態(tài)值。
參照:
Attributes vs. Properties

2017年9月26日 02:32