DIV CSS 佈局教程網

用 jQuery 實作核取方塊全選、全不選、反選的關鍵解析
編輯:JQuery特效代碼     

想用 jQuery 實作核取方塊的全選、全不選與反選時,一開始我用了 attr("checked", true/false),卻發現全選只能生效一次,全不選可以,反選則完全達不到效果,除錯好久仍不對。最後才發現關鍵:jQuery 1.7.2 之前才支援用 attr 操作這類固有屬性,之後的版本必須改用 prop。

以下附上我的程式碼供參考:

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>全選、全不選、反選</title> <style type="text/css"> #choose input { display: block; } </style> <script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ var $choose = $("#choose input"); //全選 $("#all").click(function(){ $choose.each(function(){ $(this).prop("checked",true); }); }); //全不選 $("#not").click(function(){ $choose.prop("checked",false); }); //反選 $("#reverse").click(function(){ $choose.each(function(){ $(this).prop("checked",!$(this).prop("checked")); }); }); }); </script> </head> <body> <div id="box-function"> <input id="all" type="button" value="全選" /> <input id="not" type="button" value="全不選" /> <input id="reverse" type="button" value="反選" /> </div> <div id="choose"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> </body> </html>

重點提醒:處理核取方塊的勾選狀態時,請優先使用 prop() 而非 attr(),才能正確支援全選、全不選與反選。歡迎各位前輩批評指正!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved