jquery设置input只读
使用jQuery设置input只读的方法
通过jQuery可以轻松地设置input元素为只读状态,以下是几种常见的方法:
方法1:使用prop()方法
$('#inputId').prop('readonly', true);
方法2:使用attr()方法
$('#inputId').attr('readonly', 'readonly');
方法3:直接设置属性
$('#inputId')[0].readOnly = true;
方法4:动态切换只读状态

$('#toggleButton').click(function() {
$('#inputId').prop('readonly', function(i, val) {
return !val;
});
});
注意事项
prop()方法是推荐的方式,因为它直接操作DOM属性,性能更好。- 如果需要移除只读属性,可以使用
$('#inputId').prop('readonly', false);或$('#inputId').removeAttr('readonly');。 - 确保在DOM加载完成后执行jQuery代码,可以将代码放在
$(document).ready()或简写的$(function() { ... });中。






