简体   繁体   English

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

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

The following code to add and remove the property readonly works (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');作为$('#someid').prop('readonly'); doesn't work.不起作用。 What is the code to do it properly?正确执行此操作的代码是什么?

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 readonly property appropriately, and if you inspect the element in the console you'll see that the readonly attribute is added without a value like it should be according to the W3C specifications.它适当地设置了readonly属性,如果您检查控制台中的元素,您将看到添加了readonly属性,但没有按照 W3C 规范应有的值。

readonly is a property, and prop() is the method for setting properties. readonly一个属性, prop()是设置属性的方法。

The specifications for HTML5 says: HTML5 的规范说:

readonly = "readonly" or "" (empty string) or empty readonly = "readonly" 或 ""(空字符串)或空
Specifies that element represents a control whose value is not meant to be edited.指定该元素表示其值不可编辑的控件。

this means the following is valid:这意味着以下内容有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM