jquery checkbox無法用attr()二次勾選問題的解決方法
今晨,漂亮的測試妹妹提了個奇怪的bug,說我一功能checkbox時隱時現(xiàn),比如第一次打開有勾選,第n次打開可能就不選了。
想到與美女有親密接觸機會,馬上雞動起來。
經(jīng)過偶層層抽次剝繭(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="./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>
關(guān)于官方文檔,見: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()二次勾選問題的解決方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- jquery操作checkbox火狐下第二次無法勾選的解決方法
- JQuery 設(shè)置checkbox值二次無效的解決方法
- jQuery 更改checkbox的狀態(tài),無效的解決方法
- jquery中checkbox全選失效的解決方法
- 多個jquery.datatable共存,checkbox全選異常的快速解決方法
- JQuery觸發(fā)radio或checkbox的change事件
- jQuery判斷checkbox是否選中的3種方法
- JQuery對checkbox操作 (循環(huán)獲?。?/a>
- jquery操作復選框(checkbox)的12個小技巧總結(jié)
- JQUERY復選框CHECKBOX全選,取消全選
- Jquery遍歷checkbox獲取選中項value值的方法
- jQuery操作CheckBox的方法介紹(選中,取消,取值)
- jQuery中checkbox反復調(diào)用attr(''checked'', true/false)只有第一次生效的解決方法
相關(guān)文章
jQuery-ui插件sortable實現(xiàn)自由拖動排序
這篇文章主要為大家詳細介紹了jQuery-ui插件sortable實現(xiàn)自由拖動排序,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12