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

时间:2016-11-07 21:54:02

标签: javascript

在没有回答的情况下在SE上看到类似的问题。

如果我单击代码中的按钮,我会提醒字符串,并在警报中使用换行符进行格式化。然后将字符串粘贴到textarea中时,将删除所有换行符。

 SELECT r.x1 AS x1a
      , r.x2 AS x2a
      , r.y1 AS y1a
      , r.y2 AS y2a 
   FROM region r
  WHERE r.series_id =  ?  -- series_id_a parameter
    AND EXISTS ( SELECT 1
                   FROM region q
                  WHERE q.series_id =  ? -- series_id_b parameter
                    AND q.x1 = r.x1
                    AND q.x2 = r.x2
                    AND q.y1 = r.y1
                    AND q.y2 = r.y2
                )
function pasteText() {
    
  var theText = "a\nb\nc";
  alert(theText);
  document.getElementById("theText").innerText = theText;
}

注意:这只是Firefox中的一个问题

1 个答案:

答案 0 :(得分:0)

  1. 使用textContent而不是innerText
  2. 请参阅下面的代码段

    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. 或innerHTML
    2. function pasteText() {
          
        var theText = "a\nb\nc";
        alert(theText);
        document.getElementById("theText").innerHTML = theText;
      }
      <textarea id="theText"></textarea>
      <br><button onclick="pasteText()">Click</button>