val()与textarea的text()(val() vs. text() for textarea)

编程入门 行业动态 更新时间:2024-10-28 07:20:33
val()与textarea的text()(val() vs. text() for textarea)

我正在使用jQuery,并且想知道是否应该使用val()或text()(或另一种方法)来读取和更新textarea的内容。

我已经尝试过两次,我已经遇到了这两个问题。 当我使用text()来更新textarea时,换行符(\ n)不起作用。 当我使用val()来检索textarea内容时,如果文本太长,文本将被截断。

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.

最满意答案

设置/获取文本区域的值的最佳方法是.val()方法。

.text()内部使用.textContent (或.innerText for 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

.val()使用的value 属性总是显示当前的可见值,而text()的返回值可能是错误的。

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.

更多推荐

本文发布于:2023-07-04 10:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:val   textarea   text

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!