简体   繁体   English

从粘贴到textarea的javascript字符串保留换行符

[英]Preserve line breaks from javascript string on paste into textarea

Seen similar questions on SE without an answer. 在没有答案的情况下在SE上看到类似的问题。

If I click the button in the code, I alert the string and it's formatted with line breaks in the alert. 如果我单击代码中的按钮,我会提醒字符串,并在警报中使用换行符进行格式化。 When the string is then pasted into the textarea, all line breaks are removed. 然后将字符串粘贴到textarea中时,将删除所有换行符。

 function pasteText() { var theText = "a\\nb\\nc"; alert(theText); document.getElementById("theText").innerText = theText; } 
 <textarea id="theText"></textarea> <br><button onclick="pasteText()">Click</button> 

NOTE: This is only an issue in Firefox 注意:这只是Firefox中的一个问题

  1. Use textContent instead of innerText 使用textContent而不是innerText

See snippet below 请参阅下面的代码段

 function pasteText() { var theText = "a\\nb\\nc"; alert(theText); document.getElementById("theText").textContent = theText; } 
 <textarea id="theText"></textarea> <br><button onclick="pasteText()">Click</button> 

  1. or innerHTML 或innerHTML

 function pasteText() { var theText = "a\\nb\\nc"; alert(theText); document.getElementById("theText").innerHTML = theText; } 
 <textarea id="theText"></textarea> <br><button onclick="pasteText()">Click</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM