今天在写“记住密码”部分是,用到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() 不能用于普通对象,数组,窗口,文档什么玩意的,要重新获取改变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() | √ | |