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

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

本文关键字:W3C 标准 JQuery 何使用 Javascript 只读属性 添加      更新时间:2023-09-26

以下代码用于添加和删除属性readonly工作(从这里获取):

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

但是 W3C 标准建议使用不带值的只读属性(从这里获取):

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

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

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

正确的方法是:

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

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

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

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

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

它会适当地设置 readonly 属性,如果您在控制台中检查元素,您将看到添加的 readonly 属性没有根据 W3C 规范应具有的值。

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

HTML5的规范说:

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

这意味着以下内容有效:

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