使用 jquery 使 textarea 只读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3297923/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:11:19  来源:igfitidea点击:

Make textarea readonly with jquery

jquery

提问by Hacker

For text inputI do:

对于文本,input我这样做:

$('input[type="text"]').each(function(){
  $(this).attr('readonly','readonly');
});

But what should I do for textarea, to make it readonly.

但我该怎么做textarea,才能做到readonly

回答by Nick Craver

Include it in your selector (using a multiple/elementselector), like this:

将它包含在您的选择器中(使用多个/元素选择器),如下所示:

$('input[type="text"], textarea').attr('readonly','readonly');

You can test it here, if it's the onlything you're doing, there's no need for a .each(), you can just call .attr()on all matched elements.

您可以在这里测试它,如果这是您唯一要做的事情,则不需要 a .each(),您可以调用.attr()所有匹配的元素。

回答by Manu Manjunath

In latest versions of jQuery, the use of method propis preferred over use of attr.

在最新版本的 jQuery 中,使用 methodprop优于使用attr.

To make a particular textarea readonly:
$('#mytextarea1').prop('readonly', true);

要使特定的 textarea 只读:
$('#mytextarea1').prop('readonly', true);

To make all textareas readonly:
$('textarea').prop('readonly', true);

使所有文本区域只读:
$('textarea').prop('readonly', true);

To make all 'text' fields readonly:
$('input[type=text]').prop('readonly', true);

将所有“文本”字段设为只读:
$('input[type=text]').prop('readonly', true);

To make all 'text' fields and textarea readonly:
$('input[type=text],textarea').prop('readonly', true);

将所有“文本”字段和文本区域设为只读:
$('input[type=text],textarea').prop('readonly', true);

Please also note the difference between 'readonly' and 'disabled' in terms of appearance:

另请注意“只读”和“禁用”在外观上的区别:

Below is a <textarea>with disabledset to true:
Textarea disabled(looks different from a regular textarea)

下面是一个<textarea>disabled设置为true
禁用文本区域(看起来不同于常规的文本域)

Below is a <textarea>with readonlyset to true:
textarea readonly(looks same as a regular textarea)

下面是一个<textarea>readonly设置为true
文本区只读(看起来像常规的textarea)

回答by Doctor Rudolf

From Jquery 1.6 use

从 Jquery 1.6 使用

$("#mytxtarea").prop("disabled", true);

Visit http://api.jquery.com/prop/

访问http://api.jquery.com/prop/

回答by Gopi

Try this

尝试这个

$("#mytxtarea").attr("disabled", "disabled");

回答by Mehedi hasan

You can write

你可以写

$("textarea").attr("readonly", "readonly");

this will make readonly to all textarea fields.

这将使所有 textarea 字段只读。