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() )  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值