Javascript - добавление разрывов строк в строки массивов - PullRequest
0 голосов
/ 19 января 2019

У меня есть скрипт, который отображает случайное предложение при нажатии кнопки.Я хотел бы добавить разрыв строки для некоторых предложений.Пример:

"Это первое предложение"

становится:

"Это
первое предложение"

Я пытался использовать \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>

1 Ответ

0 голосов
/ 19 января 2019

Если вы назначите вашу цитату в поле textContent вашего абзаца p, она будет отображаться в виде простого текста. Если вместо этого вы используете 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>
...