使用jQuery库时,什么时候用attr() 什么时候用 prop() ?

aries 发表于 2015-03-25 1616 次浏览 标签 : jQueryattrprop

一直都在用 jQuery 1.8.3 的版本,没有尝试过 jQuery 1.9.0 的版本。

于是,开始调试代码,在 1.9.0 的版本中:

<input type="checkbox" />
<script>
    $(function() {
        $('input').click(function() {
            $(this).attr('checked');
        });
    });
</script>

点击 checkbox,结果都是 undefined

而在 1.8.3 的版本中,结果是 checked 和 undefined

到这里,问题答案找到了,就是使用 attr() 方法的问题,于是查看官方文档, 才知道从 jQuery 1.6 开始新增了一个方法 prop(),但是一直都没有使用过。

从中文意思看,两者分别是获取/设置 attributes 和 properties 的方法,那么为什么还要增加 prop() 方法呢?

Before jQuery1.6, the .attr() method sometimes took propertyvaluesinto accountwhenretrieving some attributes, which could cause inconsistent behavior.
因为在 jQuery 1.6 之前,使用 attr() 有时候会出现不一致的行为。

那么,什么时候使用attr(),什么时候使用prop()?

To retrieveandchange DOM properties suchasthe checked, selected,ordisabled state of form elements,usethe .prop() method.

根据官方的建议:具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr(),具体情况见下面的表格。

0条评论

如需评论,请填写表单。
换一个

记住我的信息