实践过程
当点击左上方那个checkBox时,要将下面的checkBox全部选中,我们的代码是这样的
然并卵,一点效果都没有,后来换成这样,好了
于是上官方的文档查了下attr和prop的区别,发现根本看不懂,如下图
于是,我们做了个实验
c2:
c3:Box" type="checkBox" checked=""/>
c4:
c5:
c6:
var a1=$("#c1").attr("checked");
var a2=$("#c2").attr("checked");
var a3=$("#c3").attr("checked");
var a4=$("#c4").attr("checked");
var a5=$("#c5").attr("checked");
var a6=$("#c6").attr("checked");
var p1=$("#c1").prop("checked");
var p2=$("#c2").prop("checked");
var p3=$("#c3").prop("checked");
var p4=$("#c4").prop("checked");
var p5=$("#c5").prop("checked");
var p6=$("#c6").prop("checked");
console.log("a1:"+a1);
console.log("a2:"+a2);
console.log("a3:"+a3);
console.log("a4:"+a4);
console.log("a5:"+a5);
console.log("a6:"+a6);
console.log("p1:"+p1);
console.log("p2:"+p2);
console.log("p3:"+p3);
console.log("p4:"+p4);
console.log("p5:"+p5);
console.log("p6:"+p6);
结果是这样的(chrome)
发现attr的返回值要么是checked要么是undefined,prop的返回值只有true和false。
经过在网上搜素和测试总结
prop()函数的结果:
2.如果没有相应的属性,返回值是空字符串。
attr()函数的结果:
2.如果没有相应的属性,返回值是undefined。
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
具有 true 和 false 两个属性的属性,如 checked,selected 或者 disabled 使用prop()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持。