今晨,漂亮的測試妹妹提了個奇怪的bug,說我一功能checkbox時隱時現,比如第一次打開有勾選,第n次打開可能就不選了。
想到與美女有親密接觸機會,馬上雞動起來。
經過偶層層抽次剝繭(da da jiang you),終于知道了原因:attr()在二次選中勾選框時,失效。
比如,如下HTML頁面,一點【選中】、二點【取消選中】、三點【選中】,瞧,不行了唄。
1.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以上),如下代碼:
2.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Attr checked</title> <script type="text/javascript" src="http://www.gimoo.net/t/1901/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/
摘抄如下:“As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.”
以上這篇jquery checkbox無法用attr()二次勾選問題的解決方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持綠夏網。