dja*_*iro 150 html javascript textarea line-breaks
我正在使用JavaScript编辑textarea.问题是,当我在其中进行换行时,它们将不会显示.我怎样才能做到这一点?
我正在获得编写函数的值,但它不会给出换行符.
TSt*_*per 259
问题来自于换行符(\n\r?)与HTML <br/>标签不同
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');
Run Code Online (Sandbox Code Playgroud)
jit*_*jit 24
如果您使用通用java脚本,则需要将字符串分配给文本区域值
document.getElementById("textareaid").value='texthere\\\ntexttext'.
Run Code Online (Sandbox Code Playgroud)
您需要更换\n或< br >以\\\n
否则它会Uncaught SyntaxError: Unexpected token ILLEGAL在所有浏览器上提供.
0lu*_*sz0 14
也许有人觉得这很有用:
我遇到了从服务器变量传递到javascript变量的换行问题,然后javascript将它们写入textarea(使用knockout.js值绑定).
解决方案是双重逃避新行:
orginal.Replace("\r\n", "\\r\\n")
Run Code Online (Sandbox Code Playgroud)
在服务器端,因为只有单个转义字符javascript没有解析.
如果你想在你自己的页面中显示文本,你可以使用<pre>标签。
document.querySelector('textarea').addEventListener('keyup', function() {
document.querySelector('pre').innerText = this.value;
});Run Code Online (Sandbox Code Playgroud)
<textarea placeholder="type text here"></textarea>
<pre style="font-family: inherits">
The
new lines will
be respected
and spaces too
</pre>Run Code Online (Sandbox Code Playgroud)
我有一个 id 为#infoartist的文本区域,如下:
\n<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>\nRun Code Online (Sandbox Code Playgroud)\n在 JavaScript 代码中,I\xe2\x80\x99ll 获取文本区域的值,并用标签替换转义新行(\\n\\r)<br />,例如:
var text = document.getElementById("infoartist").value;\ntext = text.replace(/\\r?\\n/g, \'<br />\');\nRun Code Online (Sandbox Code Playgroud)\n所以如果你使用jQuery(像我一样):
\nvar text = $("#infoartist").val();\ntext = text.replace(/\\r?\\n/g, \'<br />\');\nRun Code Online (Sandbox Code Playgroud)\n