我正在用 JavaScript 编辑 <textarea>。问题是,当我在其中使用换行符时,它们不会显示出来。我怎么能这么做?
<textarea>
我得到了一个写函数的值,但它不会给出换行符。
对于 textarea中的 linebreaks,您需要使用 \n
textarea
linebreaks
\n
新行对于浏览器来说只是空格,不会与普通空格(“”)有任何区别。要获得新行,必须插入 <BR />元素。
<BR />
另一种解决这个问题的方法是: 在文本区域中输入文本,然后在按钮后面添加一些 JavaScript,将不可见的字符转换为可读的字符,并将结果转储到 DIV中。它会告诉你你的浏览器想要什么。
DIV
问题在于换行符(\n\r?)与 HTML <br/>标记不同:
\n\r
<br/>
var text = document.forms[0].txt.value; text = text.replace(/\r?\n/g, '<br />');
由于许多评论和我自己的经验告诉我,这个 <br>解决方案并不像预期的那样工作,这里有一个如何使用’r n’向 textarea追加新行的示例:
<br>
function log(text) { var txtArea; txtArea = document.getElementById("txtDebug"); txtArea.value += text + '\r\n'; }
如果您使用通用 JavaScript,并且需要将一个字符串分配给一个文本区域值,那么 GetElementById (“ textareaid”) . value = ‘ texthere ntexttext’。
你需要用 \\\n代替 \n或 < br >。
\\\n
< br >
否则,它会在所有浏览器中给出 未捕获的语法错误: 意外令牌非法。
如果您只是需要向服务器发送带有换行符的 textarea 值,请使用 Nl2br。
我遇到了一个问题,从一个服务器变量传递到一个 JavaScript 变量的换行符,然后 JavaScript 将它们写到一个 text 区域(使用 帅哥值绑定)。
解决办法是双重逃避新的路线:
original.Replace("\r\n", "\\r\\n")
在服务器端,因为只有单个转义字符,JavaScript 没有解析。
这是我为同样的麻烦所做的事。
当我将文本传递到 JSP中的下一页时,我将它作为文本区域来阅读,而不是像这样阅读
<s:property value="%{text}"/>
所以输出是你想要的。
对于其他属性,可以使用如下所示。
<textarea style="background-color: white; border: none; width:660px;font-family: Arial, Helvetica, sans-serif; font-size:1.0em; resize:none;" name="text" cols="75" rows="15" readonly="readonly" ><s:property value="%{text}"/></textarea>
我有一个 id 为 # 信息艺术家的文本区域,如下所示:
<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>
在 JavaScript 代码中,我将获得 textarea 的值,并通过 <br />标记替换转义新行(n r) ,例如:
<br />
var text = document.getElementById("infoartist").value; text = text.replace(/\r?\n/g, '<br />');
因此,如果你正在使用 JQuery(像我一样) :
var text = $("#infoartist").val(); text = text.replace(/\r?\n/g, '<br />');
如果希望在自己的页面中显示文本,可以使用 <pre>标记。
<pre>
document.querySelector('textarea').addEventListener('keyup', function() { document.querySelector('pre').innerText = this.value; });
<textarea placeholder="type text here"></textarea> <pre style="font-family: inherits"> The new lines will be respected and spaces too </pre>