jQuery 设置然后读取文本框上的只读属性
<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
进一步到 这里的问题,我无法让解决方案起作用,因为 jQuery 似乎没有未正确设置只读属性(或至少一致)。
请注意,我使用 $('#test').attr('readonly', true);
得到相同的结果,
我使用的是 Chrome,readonly 属性呈现为 readonly=""
。这里还有另一篇文章表明 FireFox 也这样做。
我对此并不太担心,因为它仍然阻止文本框可编辑,但我无法找到一种方法来检测只读属性。
我通常喜欢 jQuery,但这有点 WTF。
有什么想法吗?
<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).
Note I get the same results with $('#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.
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.
I normally love jQuery but this is all a bit WTF.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人不会使用removeAttr()...我只是用attr()将其设置为false。
然后,您可以正常查询属性:
此外,您可以继续使用removeAttr(),然后仅使用长度作为检测属性的方法:
如果您担心选择器,则应该将选择器语法设置为 < code>:not([readonly='readonly']) 编辑: 我看到这已经在您引用的答案中了。
I personally wouldn't use removeAttr()...I'd just set it to false with attr().
You could then just query the property normally:
Also, you can keep using removeAttr(), and then just use the length as a way to detect the property:
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.我认为即使您设法使用 Javascript 以编程方式禁用输入,如果聪明的用户禁用浏览器 JavaScript,他们也将能够更改它。因此为了安全起见,最好在服务器端重新加载该值。
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.