jquery 获取checkbox的checked属性总是undefined
項(xiàng)目中用的jquery1.9 今天需要檢測(cè)一個(gè)checkbox的選中狀態(tài),想當(dāng)然的用 .attr("checked") ,結(jié)果發(fā)現(xiàn),無(wú)論是否選中,這個(gè)值都是 undefined 未定義。
折騰了半天,無(wú)奈,只能取jq官網(wǎng)看看文檔,發(fā)現(xiàn)有這么一段說(shuō)明
As of jQuery 1.6, the?.attr()?method returns?undefined?for attributes that have not been set. In addition,?.attr()?should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the?.prop()method.
注意最后兩句話,說(shuō)什么.attr() 不能用于普通對(duì)象,數(shù)組,窗口,文檔什么玩意的,要重新獲取改變dom屬性,用.prop()方法。
ok,雖然不太明白它說(shuō)的具體含義是什么,但是看到.prop方法姑且一試吧,結(jié)果還真可以,若選中則返回true否則返回false。
代碼貼上來(lái),有興趣可自行測(cè)試:
<html xmlns="http://www.w3.org/1999/xhtml"><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script><script>$(function(){$("#clk").click(function(){alert($("#ckb").prop("checked"));})})</script></head><body><input type="button" value="click" id="clk"><input type="checkbox" id="ckb"/></body> </html>?
轉(zhuǎn)載于:https://www.cnblogs.com/jsonzheng/p/3655874.html
總結(jié)
以上是生活随笔為你收集整理的jquery 获取checkbox的checked属性总是undefined的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第 3 章 第 2 题 求级数问题 递归
- 下一篇: 对Bootloader(引导加载程序)的