jquery设置只读
使用 jQuery 设置只读属性
通过 jQuery 可以轻松设置表单元素的只读属性,以下是几种常见方法:
设置只读属性
$('#inputId').prop('readonly', true);
移除只读属性
$('#inputId').prop('readonly', false);
使用 attr 方法(旧版 jQuery)
$('#inputId').attr('readonly', 'readonly');
移除只读属性(attr 方法)
$('#inputId').removeAttr('readonly');
批量设置只读
$('input').prop('readonly', true);
注意事项
prop()方法在 jQuery 1.6+ 中推荐使用attr()方法适用于旧版 jQuery- 只读属性不会阻止程序修改值,仅限制用户输入
动态切换只读状态
可以通过事件触发来动态切换只读状态:
$('#toggleButton').click(function() {
$('#inputId').prop('readonly', function(i, val) {
return !val;
});
});
设置禁用状态替代方案
如果需要完全禁用元素交互,可以使用 disabled 属性:

$('#inputId').prop('disabled', true);
这些方法适用于所有表单元素,包括 input、textarea 和 select 等。






