Val()和 text()对于 textarea

我正在使用 jQuery,不知道是否应该使用 val ()或 text ()(或其他方法)来读取和更新文本区域的内容。

我都试过了,但都有问题。当我使用 text ()来更新 textarea 时,换行符(n)不起作用。当我使用 val ()检索 textarea 内容时,如果文本太长,就会被截断。

137138 次浏览

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() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.