attr全選第三次失效
阿新 • • 發佈:2017-09-04
button bsp html switch 解決 取消 size 代碼 1.2
一功能checkbox時隱時現,比如第一次打開有勾選,第n次打開可能就不選了。
經過偶層層抽次剝繭(da da jiang you),終於知道了原因:attr()在二次選中勾選框時,失效。
比如,如下HTML頁面,一點【選中】、二點【取消選中】、三點【選中】,瞧,不行了唄。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>prop demo</title> <style> img { padding: 10px; } div { color: red; font-size: 24px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <input type="checkbox" checked="checked"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox" checked="checked"> <script> $( "input[type=‘checkbox‘]" ).prop( "checked", function( i, val ) { return !val; }); </script> </body> </html>
解決方案,是使用prop()替換attr()方法(在Jquery1.6以上),如下代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Attr checked</title> <script type="text/javascript" src="./js/jquery-1.11.2.js"></script> <script type="text/javascript"> function switchChecked(flag) { $("input[type=‘checkbox‘]").prop(‘checked‘, flag); } </script> </head> <body> <input type="checkbox" /> <input type="button" onclick="switchChecked(true)" value="選中"> <input type="button" onclick="switchChecked(false)" value="取消選中"> </body> </html>
關於官方文檔,見:http://api.jquery.com/attr/
或者http://api.jquery.com/prop/
轉自:http://www.cnblogs.com/nick-huang/p/4436421.html
attr全選第三次失效