使用 jquery 1.6 .prop() 将控件设置为只读
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5891734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting a control to readonly using jquery 1.6 .prop()
提问by ajbeaven
With the release of jQuery 1.6, the recommendation on SO has been to generally start using prop() where you used to use attr().
随着 jQuery 1.6 的发布,关于 SO 的建议是通常开始使用 prop(),而你曾经使用过 attr()。
What happens when I want make an element readonly?
当我想让一个元素只读时会发生什么?
$('.control').prop('readonly', 'readonly');
$('.control').prop('readonly', true);
Neither of these seem to make the control readonly. Is making an element readonly the exception to the rule?
这些似乎都没有使控件只读。使元素只读是规则的例外吗?
回答by aroth
The problem is that the property name is case-sensitive. Try:
问题是属性名称区分大小写。尝试:
$('.control').prop('readOnly', true);
Though really I don't know why this requires jQuery. This works just as well:
虽然我真的不知道为什么这需要 jQuery。这也同样有效:
document.getElementsByClassName("control")[0].readOnly = true;
回答by Code Maverick
Try this:
尝试这个:
$(".control").prop({ readOnly: true });
I think of it like this: .attr()gets the default value in the html markup while .prop()gets/sets the value dynamically. Look at the following:
我认为它是这样的:.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
The api documentation says this:
api 文档是这样说的:
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() only retrieves attributes.
属性和特性之间的差异在特定情况下可能很重要。在 jQuery 1.6 之前,.attr() 方法在检索某些属性时有时会考虑属性值,这可能会导致不一致的行为。从 jQuery 1.6 开始, .prop() 方法提供了一种显式检索属性值的方法,而 .attr() 仅检索属性。