在< textarea>中设置文本,包括换行符 [英] Set text in <textarea>, including newlines

查看:126
本文介绍了在< textarea>中设置文本,包括换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在js函数的<textarea>中设置文本;我只是将innerText属性设置为新值.文本为多行,应按原样显示.但是,浏览器会删除换行符,并且整个文本显示为一行:

I want to set the text in a <textarea> from a js-function; I'm simply setting the innerText-attribute to a new value. The text is multiline and should be displayed as such. However, newlines are dropped by the browser and the entire text is displayed as one line:

document.getElementById("my_textarea1").innerText = "foo\nbar"; // displayed as "foobar"

document.getElementById("my_textarea2").innerText = "foo\
    bar"; // displayed as "foobar"

document.getElementById("my_textarea3").innerText = `foo\
    bar`; // again, "foobar"

<textarea id="my_textarea1"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>

<textarea>中设置文本时是否可以保留换行符?

Is there a way to preserve newlines when setting the text in a <textarea>?

推荐答案

尝试一下.我使用属性值"或"innerHTML"或"textContent":

Try it. I use property "value" or "innerHTML" or "textContent":

var area = document.getElementById("my_textarea");
area.value = "foo\nbar";

var area_2 = document.getElementById("my_textarea_2");
area_2.innerHTML = "foo\nbar";

var area_3 = document.getElementById("my_textarea_3");
area_3.textContent = "foo\nbar";

<textarea id="my_textarea"></textarea>
<textarea id="my_textarea_2"></textarea>
<textarea id="my_textarea_3"></textarea>

这篇关于在&lt; textarea&gt;中设置文本,包括换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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