關於checkbox全選與全不選遇到的問題

來源:互聯網
上載者:User

標籤:alert   匹配   move   type   hang   .net   his   16px   方法   

HTML:

  <div class="outbox">

    <label for="box">全選</label>

    <input type="checkbox" id="box"/>

  </div>

  <div class="outbox2">

    <label for="box1">選項1</label>

    <input type="checkbox" id="box1" name="goods"/>

    <label for="box2">選項2</label>

    <input type="checkbox" id="box2" name="goods"/>

  </div>

第一種方法:

  $("#box).click(function(){

    if($(this).is(":checked)){

      $("input[name=‘goods‘]").attr("checked","checked");

    }else{

      $("input[name=‘goods‘]").removeAttr("checked","checked");

    }

  })

  本以為這種方法能完成全選與全不選的功能,但是當第一次點擊時,能正確全選,再點擊也能正確全不選;但是當再次點擊的時候,就不能全選與全不選了,點了完全沒作用。找不到原因是什麼!

第二種方法:

  $("#box).click(function(){

    if(this.checked){

      $("input[name=‘goods‘]").each(function(){

        this.checked=true;

      })

    }else{

      $("input[name=‘goods‘]").each(function(){

        this.checked=false;

      })

    }

  })

  這種方法就能正確的實現全選與全不選的功能了。這又是為什麼呢?

第三種方法:

 1)$("#box).change(function(){

    $("input[name=‘goods‘]").prop("checked",this.checked);

  })

 2)$("#box).click(function(){

    if($(this).is(":checked")){

      $("input[name=‘goods‘]").prop("checked",true);

    }else{

      $("input[name=‘goods‘]").prop("checked",false);

    }

  })

  

  或者是把prop裡的布爾值,true改成“checked”,false改成 “ ”。也可已實現全選與全不選的功能。

 

疑問:為什麼prop就可以直接賦值,而attr這樣賦值就不行呢?

  我一開始的時候,checkbox是未選中狀態,alert($("#box").attr("checked"))一直返回的是defined,但是alert($("#box").prop("checked"))返回的就是false;這是為什麼捏?

  有位網友也遇到過類似的問題,連結:http://www.jb51.net/article/51136.htm

  原因是在jquery1.6版本,對checked屬性在頁面初始化的時候已經初始化好了,不會隨著狀態的改變而改變。也就是說如果checkbox在頁面載入完畢是選中的,那麼返回的永遠都是選中狀態,但是如果一開始就沒有被選中,返回的永遠是undefined。

 

  prop()函數用於設定或返回當前jq對象所匹配的元素的屬性值,該函數屬於jq對象。如果要刪除DOM元素的屬性,就用removeProp()函數

  prop()與attr()的區別:連結:http://www.365mini.com/page/jquery-attr-vs-prop.htm

關於checkbox全選與全不選遇到的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.