jquery checkbox無法用attr()二次勾選問題的解決方法
今晨,漂亮的測(cè)試妹妹提了個(gè)奇怪的bug,說我一功能checkbox時(shí)隱時(shí)現(xiàn),比如第一次打開有勾選,第n次打開可能就不選了。
想到與美女有親密接觸機(jī)會(huì),馬上雞動(dòng)起來。
經(jīng)過偶層層抽次剝繭(da da jiang you),終于知道了原因:attr()在二次選中勾選框時(shí),失效。
比如,如下HTML頁面,一點(diǎn)【選中】、二點(diǎn)【取消選中】、三點(diǎn)【選中】,瞧,不行了唄。
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/
或者h(yuǎn)ttp://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()二次勾選問題的解決方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- jquery操作checkbox火狐下第二次無法勾選的解決方法
- JQuery 設(shè)置checkbox值二次無效的解決方法
- jQuery 更改checkbox的狀態(tài),無效的解決方法
- jquery中checkbox全選失效的解決方法
- 多個(gè)jquery.datatable共存,checkbox全選異常的快速解決方法
- JQuery觸發(fā)radio或checkbox的change事件
- jQuery判斷checkbox是否選中的3種方法
- JQuery對(duì)checkbox操作 (循環(huán)獲?。?/a>
- jquery操作復(fù)選框(checkbox)的12個(gè)小技巧總結(jié)
- JQUERY復(fù)選框CHECKBOX全選,取消全選
- Jquery遍歷checkbox獲取選中項(xiàng)value值的方法
- jQuery操作CheckBox的方法介紹(選中,取消,取值)
- jQuery中checkbox反復(fù)調(diào)用attr(''checked'', true/false)只有第一次生效的解決方法
相關(guān)文章
基于JQuery.timer插件實(shí)現(xiàn)一個(gè)計(jì)時(shí)器
基于JQuery.timer插件實(shí)現(xiàn)一個(gè)計(jì)時(shí)器,需要的朋友可以參考下。2010-04-04Jquery實(shí)現(xiàn)的一種常用高亮效果示例代碼
本篇文章只要是對(duì)Jquery實(shí)現(xiàn)的一種常用高亮效果示例代碼進(jìn)行了介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2014-01-01jQuery-ui插件sortable實(shí)現(xiàn)自由拖動(dòng)排序
這篇文章主要為大家詳細(xì)介紹了jQuery-ui插件sortable實(shí)現(xiàn)自由拖動(dòng)排序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12