jQuery textarea 的 val() 与 text()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8854288/
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
val() vs. text() for textarea
提问by Christophe
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.
我正在使用 jQuery,想知道是否应该使用 val() 或 text()(或其他方法)来读取和更新 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.
我已经尝试了两者,但两者都有问题。当我使用 text() 更新 textarea 时,换行符 (\n) 不起作用。当我使用 val() 检索 textarea 内容时,如果文本太长,则会被截断。
回答by Rob W
The best way to set/get the value of a textarea is the .val()
, .value
method.
设置/获取 textarea 值的最佳方法是.val()
,.value
方法。
.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:
.text()
内部使用.textContent
(或.innerText
用于 IE)方法来获取<textarea>
. 以下测试用例说明了彼此之间的关系text()
和.val()
关系:
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.
该value
物业,通过使用.val()
始终显示当前可见的价值,而text()
“的返回值可以是错误的。
回答by Kshitij Saxena -KJ-
.val()
always works with textarea
elements.
.val()
始终与textarea
元素一起使用。
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
.text()
有时有效,有时失败!它不可靠(在 Chrome 33 中测试)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
最好的是它也.val()
可以与其他表单元素(如input
)无缝协作,而.text()
失败了。