【问题标题】:Javascript - Adding line breaks to array stringsJavascript - 向数组字符串添加换行符
【发布时间】:2019-01-19 14:29:25
【问题描述】:

我有一个脚本,在按钮单击时显示随机句子。 我想在某些句子中添加换行符。示例:

“这是第一句话”

变成:

“这是
第一句话”

我尝试过使用\n<br>,但都没有。
我还能尝试什么?

    const p = document.getElementById("sentences");
    const origSentences = ["This is the first sentence.", "This is the second sentence.", "This is the third sentence."];
    let remainingSentences = [];

    function randomSentence() {
        if (remainingSentences.length === 0) remainingSentences = origSentences.slice();
        const {
            length
        } = remainingSentences;
        const [quote] = remainingSentences.splice(Math.floor(Math.random() * length), 1);
        p.textContent = quote;
    }
<p><button onclick="randomSentence()" type="button">Random Sentence</button></p>
<p id="sentences"></p>

【问题讨论】:

    标签: javascript arrays string line-breaks


    【解决方案1】:

    如果您将引用分配给段落ptextContent 字段,它将呈现为纯文本。如果您改为使用innerHTML,它将解析并呈现您提供的任何 HTML。

    参见示例。

    const p = document.getElementById("sentences");
    const origSentences = [
      "This is the <br /> first sentence.",
      "This is the second sentence.",
      "This is the <br /> third sentence."
    ];
    let remainingSentences = [];
    
    function randomSentence() {
      if (remainingSentences.length === 0)
        remainingSentences = origSentences.slice();
      const { length } = remainingSentences;
      const [quote] = remainingSentences.splice(
        Math.floor(Math.random() * length),
        1
      );
      p.innerHTML = quote;
    }
    <p>
      <button 
        onclick="randomSentence()" 
        type="button">
        Random Sentence
      </button>
    </p>
    
    <p id="sentences"></p>

    【讨论】:

    • 谢谢!它解决了我的问题!我不知道 textContent 和 innerHTML 之间的区别。我想我还有很多东西要学。
    猜你喜欢
    • 2019-12-05
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2016-06-09
    • 2023-02-10
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多