val() 与 text() 用于 textarea [英] val() vs. text() for textarea

查看:31
本文介绍了val() 与 text() 用于 textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery,想知道是否应该使用 val() 或 text()(或其他方法)来读取和更新 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.

这两种方法我都试过了,但两者都有问题.当我使用 text() 更新 textarea 时,换行符 ( ) 不起作用.当我使用 val() 检索 textarea 内容时,如果文本太长,则会被截断.

I have tried both and I've had issues with both. When I use text() to update textarea, line breaks ( ) don't work. When I use val() to retrieve the textarea content, the text gets truncated if it's too long.

推荐答案

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

The best way to set/get the value of a textarea is the .val(), .value method.

.text() 在内部使用 .textContent(或 .innerText 用于 IE)方法来获取 的内容<文本区域>.以下测试用例说明了 text().val() 如何相互关联:

.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

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

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

这篇关于val() 与 text() 用于 textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆