使用Jquery1.9 版本 來實現全選

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   使用   os   strong   

  

  在使用Jquery實現全選以及反選的時候, 使用attr()實現的時候,在瀏覽器第一次運行可以全選,但是第二次再全選,不管用。

 通過尋找資料,用 prop()方法代替attr()方法就行了。

 注意:  

       Jquery 1.6之後,可以通過attr方法去獲得屬性,通過prop方法去獲得特性.

      在遇到要擷取或設定checked,selected,readonly和disabled等屬性時,用prop方法.

jquery1.6中新加了一個方法prop(),官方解釋只有一句話:擷取在匹配的元素集中的第一個元素的屬性值。

大家都知道有的瀏覽器只要寫disabled,checked就可以了,而有的要寫成disabled = "disabled",checked="checked",比如用attr("checked")擷取checkbox的checked屬性時選中的時候可以取到值,值為"checked"但沒選中擷取值就是undefined。

jq提供新的方法“prop”來擷取這些屬性,就是來解決這個問題的,以前我們使用attr擷取checked屬性時返回"checked"和"",現在使用prop方法擷取屬性則統一返回true和false。

那麼,什麼時候使用attr(),什麼時候使用prop()?
1.添加屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();

以下是官方建議attr(),prop()的使用:

 

Attribute/Property .attr() .prop()
accesskey √  
align √  
async √ √
autofocus √ √
checked √ √
class √  
contenteditable √  
draggable √  
href √  
id √  
label √  
location ( i.e. window.location ) √ √
multiple √ √
readOnly √ √
rel √  
selected √ √
src √  
tabindex √  
title √  
type √  
width ( if needed over .width() ) √  

以下是實現全選以及反選的Html代碼,要引用Jquery指令碼。Jquery1.6以上都行.

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <script type="text/javascript" src="jquery-1.9.1.js"></script></head><body><input type="checkbox" value="全選" id="cbAll" name="cbArea">全選<br/><input type="checkbox" value="洛龍區" name="a">洛龍區<input type="checkbox" value="澗西區" name="a">澗西區<input type="checkbox" value="吉利區" name="a">吉利區<input type="checkbox" value="西工區" name="a">西工區<input type="checkbox" value="宜陽縣" name="a">宜陽縣<input type="checkbox" value="老城區" name="a">老城區<input type="checkbox" value="回族區" name="a">回族區<input type="checkbox" value="偃師" name="a">偃師<input type="checkbox" value="哈哈區" name="a">哈哈區<input type="checkbox" value="洛寧區" name="a">洛寧區</body></html><script type="text/javascript">    $(function () {        $("#cbAll").click(function () {            if($("#cbAll").is(":checked")) {                $(":checkbox").prop("checked",true);            }            else {                $(":checkbox").prop("checked", false);            }        });        $(":checkbox").click(function () {            if (!$(this).is(":checked")) {                $("#cbAll").prop("checked", false);            }        });    })</script>
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.