我怎样才能将
readonly
添加到特定的<input>
中?.attr('readonly')
不起作用。readonly
添加到特定的<input>
中?.attr('readonly')
不起作用。jQuery <1.9
$('#inputId').attr('readonly', true);
jQuery 1.9+
$('#inputId').prop('readonly', true);
阅读有关prop和attr之间的区别的更多信息。
使用$.prop()
$("#descrip").prop("readonly",true);
$("#descrip").prop("readonly",false);
$.prop()
时需要注意:prop
会将 readonly
属性设置为空字符串,因此如果您有任何使用属性选择器 [readonly="readonly"]
的 CSS,那么您需要将其更改为 [readonly]
(或同时包含两者)。 - LukeReadonly是HTML中定义的属性,因此应该像对待其他属性一样对待它。
如果您不希望对象可编辑,则需要在您正在使用的对象中添加类似readonly="readonly"的内容。如果您想要再次编辑它,则不应该使用类似readonly=''的内容(如果我理解正确,这不是标准)。您确实需要完全删除该属性。
因此,在使用jQuery时,添加和删除readonly属性是有意义的。
设置只读属性:
$("#someId").attr('readonly', 'readonly');
移除只读属性:
$("#someId").removeAttr('readonly');
这是唯一对我真正起作用的选择。希望能帮到你!
.attr('readonly', 'readonly')
应该可以解决问题。你的 .attr('readonly')
只返回值,而不是设置值。
.attr
值应该只是字符串或数字,而不是布尔值:http://api.jquery.com/attr/#attr2 此外,HTML的“布尔属性”应该只是空字符串或属性的值。我认为解决方案是使用.prop()
来避免混淆。 - Luke我认为“disabled”会排除输入内容被发送到POST。
您可以使用.removeAttr方法来取消readonly属性的设置。
$('#descrip').removeAttr('readonly');
document.getElementById("box1").onchange = function(){
if(document.getElementById("box1").value == 1) {
document.getElementById("codigo").setAttribute("readonly", true);
} else {
document.getElementById("codigo").removeAttribute("readonly");
}
};
<input type="text" name="codigo" id="codigo"/>
<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
启用只读模式:
$("#descrip").attr("readonly","true");
$("#descrip").attr("readonly","");
请检查以下代码:
<input id="mail">
<script>
document.getElementById('mail').readOnly = true; // makes input readonline
document.getElementById('mail').readOnly = false; // makes input writeable again
</script>
对于 jQuery 版本 < 1.9:
$('#inputId').attr('disabled', true);
对于 jQuery 版本 >= 1.9:
$('#inputId').prop('disabled', true);