以下代码添加和删除属性readonly
作品(来自 here ):
$('#someid').prop('readonly', true);
$('#someid').removeProp('readonly');
但是 W3C 标准建议使用没有值的只读属性(来自 here ):
我们应该使用:<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 规范说:
readonly = "readonly" or "" (empty string) or empty
Specifies that element represents a control whose value is not meant to be edited.
这意味着以下是有效的:
<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
关于javascript - 如何使用 JQuery 或 Javascript 添加只读属性(但遵循 W3C 标准!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18690463/