从一个bug说jquery中的attr和prop

为了方便描述,将问题简化如下:
先上代码
<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() )

你可能感兴趣的:(jquery)