jQuery 检测输入何时具有“只读”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5422915/
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
Detect when input has a 'readonly' attribute
提问by ziiweb
I want to throw an alert when an input has a 'readonly' attribute. I have tried this:
当输入具有“只读”属性时,我想发出警报。我试过这个:
if($('input').attr('readonly') == 'readonly'){
alert("foo");
}
I think that 'if' is not even the best way to do it.
我认为“如果”甚至不是最好的方法。
回答by Richard Neil Ilagan
fastest way is to use the .is()
jQuery function.
最快的方法是使用.is()
jQuery 函数。
if ( $('input').is('[readonly]') ) { }
using [readonly]
as a selector simply checks if the attribute is defined on your element. if you want to check for a value, you can use something like this instead:
使用[readonly]
作为选择器将只检查该属性的元素上定义的。如果你想检查一个值,你可以使用这样的东西:
if ( $('input').is('[readonly="somevalue"]') ) { }
回答by keV
Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/
从 JQuery 1.6 开始,始终使用 .prop() 阅读原因:http://api.jquery.com/prop/
if($('input').prop('readonly')){ }
.prop() can also be used to set the property
.prop() 也可以用来设置属性
$('input').prop('readonly',true);
$('input').prop('readonly',false);
回答by potench
Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.
检查“只读”属性的当前值,如果它是“假”(字符串)或空(未定义或“”),则它不是只读的。
$('input').each(function() {
var readonly = $(this).attr("readonly");
if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
alert('this is a read only field');
}
});
回答by Josiah Ruddell
You can just use the attribute selector and then test the length:
您可以只使用属性选择器,然后测试长度:
$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0 // --> not ok
回答by cachaito
Try a simple way:
尝试一个简单的方法:
if($('input[readonly="readonly"]')){
alert("foo");
}
回答by fadomire
what about javascript without jQuery ?
没有 jQuery 的 javascript 怎么样?
for any input that you can get with or without jQuery, just :
对于使用或不使用 jQuery 可以获得的任何输入,只需:
input.readOnly
note : mind camelCase
注意:介意驼峰式
回答by Musa
In vanilla/pure javascript you can check as following -
在 vanilla/pure javascript 中,您可以检查如下 -
var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
alert("foo");
}
回答by Naftali aka Neal
try this:
尝试这个:
if($('input').attr('readonly') == undefined){
alert("foo");
}
if it is not there it will be undefined
in js
如果它不存在,它将undefined
在 js 中