jQuery jQuery设置然后在文本框上读取只读属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3710078/
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
jQuery set then read readonly attr on textbox
提问by fearofawhackplanet
?<input id="test" type="text" value="text" />???????????????????????????????????????????????????????????????????????????
alert(?$(':input:not([readonly])').length);????????????????? // 1
$('#test').attr('readonly', 'readonly');
alert($(':input:not([readonly])').length); // 1
$('#test').removeAttr('readonly');??????????
alert($(':input:not([readonly])').length); // 1
Further to the question here, I can't get the solution to work because it seems jQuery doesn't set the readonly attribute correctly (or at least consistently).
除了这里的问题,我无法使解决方案起作用,因为 jQuery 似乎没有正确设置 readonly 属性(或至少始终如一)。
Note I get the same results with $('#test').attr('readonly', true);
注意我得到相同的结果 $('#test').attr('readonly', true);
I'm using Chrome, and the readonly attribute renders as readonly=""
. There is another post on here which suggests FireFox does the same.
我正在使用 Chrome,并且 readonly 属性呈现为readonly=""
. 这里有另一篇文章表明 FireFox 也这样做。
I'm not much bothered about this in as much as it still stops the text box from being editable, but I can't then find a way to detect the readonly attribute.
我对此并不太在意,因为它仍然阻止文本框可编辑,但我无法找到检测 readonly 属性的方法。
I normally love jQuery but this is all a bit WTF.
我通常喜欢 jQuery,但这有点 WTF。
Any ideas?
有任何想法吗?
回答by Trafalmadorian
I personally wouldn't use removeAttr()...I'd just set it to false with attr().
我个人不会使用 removeAttr()...我只是用 attr() 将它设置为 false。
You could then just query the property normally:
然后您可以正常查询该属性:
if ($("#X").attr("readonly"))
{
execute code
}
Also, you can keep using removeAttr(), and then just use the length as a way to detect the property:
此外,您可以继续使用 removeAttr(),然后仅使用长度作为检测属性的一种方式:
if (!$("#X").attr("readonly").length)
{
execute code
}
If you're worried about the selector, you should do the selector syntax as :not([readonly='readonly'])
edit:I see that was already in the answer you cited.
如果您担心选择器,您应该将选择器语法作为:not([readonly='readonly'])
编辑:我看到这已经在您引用的答案中了。
回答by pisang
I think even though you manage to disable the input pro-grammatically using Javascript, smart user will be able to change it if their disable the browser JavaScript. So to be safe it is best to reload the value in your server side.
我认为即使您设法使用 Javascript 以编程方式禁用输入,如果他们禁用浏览器 JavaScript,聪明的用户将能够更改它。因此,为了安全起见,最好在服务器端重新加载该值。