jQuery全選與反選,且解決點擊只執行一次的問題


<html>
<head>
  <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
</head>
<body>
  <input type="checkbox" name="chk_list[]" value="1" />1
  <input type="checkbox" name="chk_list[]" value="2" />2
  <input type="checkbox" name="chk_list[]" value="3" />3
  <input type="checkbox" name="chk_list[]" value="4" />4
  <input type="checkbox" name="chk_all" id="chk_all" />全選/取消全選

<script type="text/javascript">
  $("#chk_all").click(function(){
      // 使用attr只能執行一次
      $("input[name='chk_list[]']").attr("checked", $(this).attr("checked")); 
    
      // 使用prop則完美實現全選和反選
      $("input[name='chk_list[]']").prop("checked", $(this).prop("checked"));

    // 獲取所有選中的項並把選中項的文本組成一個字符串
      var str = '';
      $($("input[name='chk_list[]']:checked")).each(function(){
          str += $(this).next().text() + ',';
      });
      alert(str);   });
</script> </body> </html>

總結:

  • 對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
  • 對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法。
  • 參考 http://www.cnblogs.com/Showshare/p/different-between-attr-and-prop.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM