jQuery .attr("checked&…

今天在寫“記住密碼”部分是,用到jQuery判斷複選框是否選中:
function remember(){
if($("#remember").attr("checked")==true){
var username = $("#username").val();
var password = $("#password").val();
//alert("添加cookies"+username+password);
$.cookie('username',username,{expires:10});
$.cookie('password',password,{expires:10});
$.cookie('rememberUser','true',{expires:10});
}
}
但是得到$("#remember").attr("checked")爲undefined,於是上網找各種方法,後來看見一文說改成prop就行了,果然。
文中還提到關於attr的用法注意事項:

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.

注意最後兩句話,說什麼.attr() 不能用於普通對象,數組,窗口,文檔什麼玩意的,要重新獲取改變dom屬性,用.prop()方法。


那麼,什麼時候使用attr(),什麼時候使用prop()?
1.添加屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();
項目中jquery升級的時候大家要注意這點!

以下是官方建議attr(),prop()的使用:

Attribute/Property .attr() .prop()
accesskey  
align  
async
autofocus
checked
class  
contenteditable  
draggable  
href  
id  
label  
location ( i.e. window.location )
multiple
readOnly
rel  
selected
src  
tabindex  
title  
type  
width ( if needed over .width() )  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章