您的位置:首页 > Web前端 > JQuery

jQuery .attr("checked&…

2015-03-19 14:37 399 查看
今天在写“记住密码”部分是,用到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()
 )
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: