27

随着 jQuery 1.6 的发布,对 SO 的建议通常是在您过去使用 attr() 的地方开始使用 prop()。

当我想让一个元素只读时会发生什么?

$('.control').prop('readonly', 'readonly');
$('.control').prop('readonly', true);

这些似乎都没有使控件成为只读的。将元素设为只读是规则的例外吗?

4

2 回答 2

49

问题是属性名称区分大小写。尝试:

$('.control').prop('readOnly', true);

虽然我真的不知道为什么这需要 jQuery。这同样有效:

document.getElementsByClassName("control")[0].readOnly = true;
于 2011-05-05T01:52:18.197 回答
12

尝试这个:

$(".control").prop({ readOnly: true });

我是这样想的:.attr()获取 html 标记中的默认值,而.prop()动态获取/设置值。请看以下内容:

<input id="someInput" readonly="readOnly" />

$(".control").attr("readOnly") // would yield "readOnly"
$(".control").prop("readOnly") // would yield true
$(".control").is(":readOnly")  // would yield true

api文档是这样说的:

属性和属性之间的区别在特定情况下可能很重要。在 jQuery 1.6 之前,.attr() 方法有时会在检索某些属性时考虑属性值,这可能会导致行为不一致。从 jQuery 1.6 开始,.prop() 方法提供了一种显式检索属性值的方法,而 .attr() 仅检索属性。

于 2011-05-05T01:51:59.740 回答