我正在使用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 testThe value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.
更多推荐
发布评论