jQuery的attr方法和prop方法区别

当点击左上方那个checkBox时,要将下面的checkBox全部选中,我们的代码是这样的

?

1

$("input[name='checkbox']").attr("checked",true);

然并卵,一点效果都没有,后来换成这样,好了

?

1

2

3

4

5

6

7

8

9

$(function(){

 $("#all").click(function(){

  if($("#all").prop("checked")){

   $("input[name='checkbox']").prop("checked",true);

  }else{

   $("input[name='checkbox']").prop("checked",false);

  }

 });

});

于是上官方的文档查了下attr和prop的区别,发现根本看不懂,如下图

于是,我们做了个实验

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

c1:<input id="c1" name="checkbox" type="checkbox" checked="checked" /></br>

c2:<input id="c2" name="checkbox" type="checkbox" checked=true/></br>

c3:<input id="c3" name="checkbox" type="checkbox" checked=""/></br>

c4:<input id="c4" name="checkbox" type="checkbox" checked/></br>

c5:<input id="c5" name="checkbox" type="checkbox" /></br>

c6:<input id="c6" name="checkbox" type="checkbox" checked=false/></br>

 

 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()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是undefined。

attr()函数的结果:

      1.如果有相应的属性,返回指定属性值。

      2.如果没有相应的属性,返回值是undefined。

对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。

对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop()

效果如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lixiaotao_1

谢谢老板!~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值