jquery實現複選框全選,全不選,反選中的問題

來源:互聯網
上載者:User

標籤:rip   for   css   分享   images   func   解決方案   false   attr   

今天試了一下用jquery選擇複選框,本來以為很簡單的東西卻有bug,於是搜尋了一下找到瞭解決方法。

html代碼如下(這裡沒有用任何樣式,就沒有再放css了):

<html>    <head>        <meta charset="utf-8">        <link rel="stylesheet" href="test_ch5.css" >        <title>test_ch5</title>    </head>    <body>        <div id="wrapper">            <form action="" method="post">                    <p>你最愛好的運動是?</p>                    <input type="checkbox" name="items" >足球                    <input type="checkbox" name="items">籃球                    <input type="checkbox" name="items">羽毛球                    <input type="checkbox" name="items">乒乓球<br>                    <input type="button" id="all" value="全 選">                    <input type="button" id="no" value="全不選">                    <input type="button" id="reverse" value="反 選">                    <input type="button" id="send" value="提 交">                </form>            </div>    </body><script src="jquery-3.2.1.js"></script><script>    $(function(){        $("#all").click(function(){            $(‘[name=items]:checkbox‘).prop(‘checked‘,true);        });        $("#no").click(function() {            $(‘[type=checkbox]:checkbox‘).prop(‘checked‘,false);        });        $("#reverse").click(function() {            $(‘input[name=items]‘).each(function(){                $(this).prop(‘checked‘,!$(this).prop(‘checked‘));            });        }); })</script></html>

介面如下:

之前不知道有prop,使用prop的地方全部用的是attr,發現實現不了想要的功能啊,然後才發現的prop,它是是jquery1.6以後出來的,用來區別之前的.attr()方法.
區別最大的一點就是:布爾型的屬性,1.6以後都是用.prop()方法就好了。
這個布爾型的屬性,再解釋一下,是屬性值只有true|false的屬性。
還有種情況就是只添加屬性名稱,不需要寫屬性值的就可以生效的也同樣使用.prop()方法。比如:checked、disable這樣的,其實它們說到底還是屬於布爾型的屬性。

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

 

jquery實現複選框全選,全不選,反選中的問題

相關文章

聯繫我們

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