【问题标题】:Is .value preventing line breaks in the textarea?.value 是否可以防止文本区域中的换行符?
【发布时间】:2015-11-18 21:50:32
【问题描述】:

如何让模板中的换行符显示在文本区域中?

我试图在, 之后的每个模板中添加一个换行符,并且我认为由于使用.value 而不能使用</ br>

我尝试了JavaScript: How to add line breaks to an HTML textarea?javascript | save textarea value with line breaks 以及使用style="white-space:pre-wrap" 的建议。

var template_Birthday = "Hey <NAME>, This is the Birthday Template.";
var template_NewJob = "Hey <NAME>, This is the New Job Template.";

var content = function() {
  var e = document.getElementById("template");
  var strUser = e.options[e.selectedIndex].value;

  if (strUser === "template_NewJob") {
    messageBodyTextarea.value = template_NewJob;
  } else if (strUser === "template_Birthday") {
    messageBodyTextarea.value = template_Birthday;
  }
};
&lt;textarea class="form-control" rows="7" name="message" id="messageBodyTextarea"&gt;&lt;/textarea&gt;

【问题讨论】:

  • 请提供小提琴?
  • \n 是换行符的转义码

标签: javascript jquery html


【解决方案1】:

使用 \n 换行。

var template_NewJob = "Hey <NAME>,\nThis is the New Job Template.";

【讨论】:

    【解决方案2】:

    由于您正在设置textArea 的值,您是否尝试过转义换行符:

    messageBodyTextarea.value = "Hey <NAME>, \nThis is the Birthday Template.";
    

    如果您将 HTML 写入 DOM,则只需使用 &lt;br /&gt;

    【讨论】:

      【解决方案3】:

      在 HTML 中为 textarea 添加换行符:

      <textarea id="myTextarea">Line 1
      Line 2
      Line 3</textarea>
      

      在 JavaScript 中为 textarea 添加换行符:

      var ta = document.getElementById('myTextarea');
      ta.value = 'Line1\nLine2\nLine3';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-24
        • 2014-04-01
        • 1970-01-01
        • 2023-03-14
        • 2011-03-23
        相关资源
        最近更新 更多