如何使用 JQuery 或 Javascript 添加 readonly 属性(但遵循 W3C 标准!)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18690463/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:13:21  来源:igfitidea点击:

How to add the readonly attribute with JQuery or Javascript (BUT following the W3C standard!)

javascriptjquery

提问by chelder

The following code to add and remove the property readonlyworks (gotten from here):

添加和删​​除属性的以下代码readonly有效(从此处获取):

$('#someid').prop('readonly', true);
$('#someid').removeProp('readonly');

But the W3C standard recommend to use the readonly attribute without a value (gotten from here):

但是 W3C 标准建议使用没有值的 readonly 属性(从这里获取):

We should use: <input type="text" readonly />

我们应该使用: <input type="text" readonly />

Instead: <input type="text" readonly="true or readonly or anything" />

反而: <input type="text" readonly="true or readonly or anything" />

As $('#someid').prop('readonly');doesn't work. What is the code to do it properly?

因为$('#someid').prop('readonly');不起作用。正确执行此操作的代码是什么?

回答by adeneo

The proper way to do it is with :

正确的做法是:

$('#someid').prop('readonly', true);

or

或者

$('#someid').prop('readonly', false);

and

$('#someid').removeProp('readonly');

works fine as well as these are all jQuery methods for the native:

工作正常,而且这些都是本机的 jQuery 方法:

document.getElementById('someid').readOnly = true;

which sets the readonlyproperty appropriately, and if you inspect the element in the console you'll see that the readonlyattribute is added without a value like it should be according to the W3C specifications.

readonly适当地设置了属性,如果您检查控制台中的元素,您将看到readonly添加的属性没有按照 W3C 规范应有的值。

readonlyisa property, and prop()is the method for setting properties.

readonly一个属性,prop()是设置属性的方法。

The specifications for HTML5 says:

HTML5 的规范说:

readonly = "readonly" or "" (empty string) or empty
Specifies that element represents a control whose value is not meant to be edited.

readonly = "readonly" 或 ""(空字符串)或空
指定该元素表示其值不可编辑的控件。

this means the following is valid:

这意味着以下内容有效:

<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />