码迷,mamicode.com
首页 > Web开发 > 详细

从一个bug说jquery中的attr和prop

时间:2015-04-10 11:28:19      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:jquery

为了方便描述,将问题简化如下:
先上代码
<form> 
<input type="checkbox">iqiyi</input>
<input type="checkbox" checked="checked">letv</input>
</form> 
<button type>showStatus</button> 

<script> 
$("button").click(function(){ 
    var list = $("form input");
    for (var i=0; i<list.length; i++){
        console.log('input ' + i + ':' + $(list[i]).attr('checked'));
    }
}) 
</script>

对应页面对图1所示
技术分享图1

代码功能很简单,点击"showStatus", 获取每个checkbox的状态。注意,这里获取状态值时,我们使用了jquery的attr函数。
不对页面中的checkbox进行操作,直接点击"showStatus", 得到结果:
input 0:undefined
input 1:checked
看起来没啥问题。

对页面进行操作,使之变成:
技术分享图2
再用"showStatus"看结果:
input 0:undefined
input 1:checked
居然没有变化!what‘s wrong!莫非jquery的attr有bug!?
几经查询,发现不是attr有问题,是我用错了api。应该使用prop, 而不是attr。
$(list[i]).attr(‘checked‘)替换为$(list[i]).prop(‘checked‘),相应图1,图2操作得到的结果是
input 0:false
input 1:true

input 0:true
input 1:false
checkedbox被勾选,得到true,未被选得到false,会随用户操作动态变化。true,false的返回值也更易使用。

附官方建议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() )

从一个bug说jquery中的attr和prop

标签:jquery

原文地址:http://blog.csdn.net/qmhball/article/details/44975753

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!