val()与textarea的text() [英] val() vs. text() for textarea
问题描述
我正在使用jQuery,并且想知道是否应该使用val()或text()(或其他方法)来读取和更新textarea的内容。
我已经尝试了两种方法,而且两者都有问题。当我使用text()更新textarea时,换行符(\\\
)不起作用。当我使用val()来检索textarea内容时,如果文本太长,文本会被截断。
设置/获取textarea的值是 .val()
, .value
方法。
.text()
内部使用 .textContent
(或 .innerText
for IE)方法来获取< textarea>
的内容。以下测试用例说明 text()
和 .val()
如何相互关联:
var t ='< textarea>';
console.log($(t).text('test')。val()); //打印测试
console.log($(t).val('too')。text('test')。val()); //打印太
console.log($(t).val('too')。text()); //打印什么
console.log($(t).text('test')。val('too')。val()); //打印太多
console.log($(t).text('test')。val('too')。text()); //打印测试
值
property ,由 .val()
总是显示当前可见值,而 text()
返回值可能是错误的。
I am using jQuery, and wondering if I should use val() or text() (or another method) to read and update the content of a textarea.
I have tried both and I've had issues with both. When I use text() to update textarea, line breaks (\n) don't work. When I use val() to retrieve the textarea content, the text gets truncated if it's too long.
The best way to set/get the value of a textarea is the .val()
, .value
method.
.text()
internally uses the .textContent
(or .innerText
for IE) method to get the contents of a <textarea>
. The following test cases illustrate how text()
and .val()
relate to each other:
var t = '<textarea>';
console.log($(t).text('test').val()); // Prints test
console.log($(t).val('too').text('test').val()); // Prints too
console.log($(t).val('too').text()); // Prints nothing
console.log($(t).text('test').val('too').val()); // Prints too
console.log($(t).text('test').val('too').text()); // Prints test
The value
property, used by .val()
always shows the current visible value, whereas text()
's return value can be wrong.
这篇关于val()与textarea的text()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!