为了方便描述,将问题简化如下:
图1
图2
先上代码
<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所示
代码功能很简单,点击"showStatus", 获取每个checkbox的状态。注意,这里获取状态值时,我们使用了jquery的attr函数。
不对页面中的checkbox进行操作,直接点击"showStatus", 得到结果:
input 0:undefined
input 1:checked看起来没啥问题。对页面进行操作,使之变成:
再用"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中使用attr与prop的不同之处,特别是针对checkbox元素的checked属性。演示了如何正确地获取DOM元素的状态,并提供了一个官方推荐的attr与prop使用指南。
1005

被折叠的 条评论
为什么被折叠?



