Setting a control to readonly using jquery 1.6 .prop()

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 05:27:33

问题


With the release of jQuery 1.6, the recommendation on SO has been to generally start using prop() where you used to use 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?


回答1:


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:

document.getElementsByClassName("control")[0].readOnly = true;



回答2:


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:

<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:

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.



来源:https://stackoverflow.com/questions/5891734/setting-a-control-to-readonly-using-jquery-1-6-prop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!