【发布时间】:2011-03-24 17:13:30
【问题描述】:
我想在输入具有“只读”属性时发出警报。我试过这个:
if($('input').attr('readonly') == 'readonly'){
alert("foo");
}
我认为“如果”甚至不是最好的方法。
【问题讨论】:
标签: jquery
我想在输入具有“只读”属性时发出警报。我试过这个:
if($('input').attr('readonly') == 'readonly'){
alert("foo");
}
我认为“如果”甚至不是最好的方法。
【问题讨论】:
标签: jquery
最快的方法是使用.is() jQuery 函数。
if ( $('input').is('[readonly]') ) { }
使用[readonly] 作为选择器只是检查该属性是否在您的元素上定义。如果你想检查一个值,你可以使用这样的东西:
if ( $('input').is('[readonly="somevalue"]') ) { }
【讨论】:
is 的反面 = not
从 JQuery 1.6 开始,始终使用 .prop() 在此处阅读原因:http://api.jquery.com/prop/
if($('input').prop('readonly')){ }
.prop() 也可以用来设置属性
$('input').prop('readonly',true);
$('input').prop('readonly',false);
【讨论】:
没有 jQuery 的 javascript 怎么样?
对于任何使用或不使用 jQuery 都可以获得的输入,只需:
input.readOnly
注意:记住camelCase
【讨论】:
检查“只读”属性的当前值,如果它是“假”(字符串)或空(未定义或“”),那么它不是只读的。
$('input').each(function() {
var readonly = $(this).attr("readonly");
if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
alert('this is a read only field');
}
});
【讨论】:
你可以只使用属性选择器,然后测试长度:
$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0 // --> not ok
【讨论】:
尝试一个简单的方法:
if($('input[readonly="readonly"]')){
alert("foo");
}
【讨论】:
试试这个:
if($('input').attr('readonly') == undefined){
alert("foo");
}
如果它不存在,它将在 js 中为 undefined
【讨论】:
在 vanilla/pure javascript 中,您可以检查如下 -
var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
alert("foo");
}
【讨论】: