1. 程式人生 > >jQuery中使用attribute,prop獲取,設置input的checked值【轉】

jQuery中使用attribute,prop獲取,設置input的checked值【轉】

attribute 原因 lib size 未定義 software eight pos -h

1、prop方法獲取、設置checked屬性

當input控件checkbox設置了checked屬性時,無論checked=”“或
checked=”checked”,$(obj).prop(“checked”)的結果都是true;
當input控件checkbox沒設置checked屬性時,$(obj).prop(“checked”)的結果是false。
設置$(“input[name=’checkboxall’]”).prop(“checked”, true)時,checkbox會被選中;
設置$(“input[name=’checkboxall’]”).prop(“checked”, false)時,checkbox不會被選中;

2、attr方法獲取、設置checked屬性

<input type="checkbox" id="selectAll" onclick="checkAll()" >全選
如果當前input中初始化未定義checked屬性,則不管當前是否選中,$(“#selectAll”).attr(“checked”)都會返回undefined;
<input type="checkbox" id="selectAll" checked="" onclick="checkAll()" >全選
<input type="checkbox" id="selectAll" checked="checked"
onclick="checkAll()" >

全選
如果當前input中初始化定義了checked屬性,無論checked=”“或
checked=”checked”,當前checkbox都處於選中狀態,
$(“#selectAll”).attr(“checked”)都會返回”checked”;

3、總結

在jquery中應該使用prop方法來獲取和設置checked屬性,不應該使用attr.

4、jquery版本原因

jquery-1.4.1.min.js、jquery-1.4.2.min.js可以用attr方法正確地獲取或設置checkbox的checked屬性,但是高版本例如:1.10.2.min.js就不能用attr方法正確地獲取或設置checkbox的checked屬性,在此聲明:其他版本沒有測試。

jQuery中使用attribute,prop獲取,設置input的checked值【轉】