国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

jquery checkbox無法用attr()二次勾選問題的解決方法

2019-11-20 09:25:55
字體:
來源:轉載
供稿:網友

今晨,漂亮的測試妹妹提了個奇怪的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="./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()二次勾選問題的解決方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 恭城| 永吉县| 琼中| 彩票| 仁怀市| 新丰县| 都兰县| 夏邑县| 监利县| 宜丰县| 桃园县| 淮南市| 抚顺市| 郯城县| 周至县| 道真| 葫芦岛市| 荣成市| 莫力| 普陀区| 六安市| 浙江省| 延边| 永定县| 阿坝| 宁蒗| 浮山县| 山西省| 景宁| 岫岩| 万山特区| 同德县| 泊头市| 凤台县| 乌拉特前旗| 乐清市| 靖西县| 凤山市| 九江市| 谷城县| 乐至县|