Javascript - 为数组字符串添加换行符
Javascript - Adding line breaks to array strings
我有一个脚本,可以在单击按钮时随机显示一个句子。
我想在某些句子中添加换行符。示例:
"This is the first sentence"
变为:
“这是
第一句话
我试过使用 \n
和 <br>
,但 none 有效。
我还能尝试什么?
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>
如果您将引用分配给段落 p
的 textContent
字段,它将呈现为纯文本。如果您改为使用 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>
我有一个脚本,可以在单击按钮时随机显示一个句子。 我想在某些句子中添加换行符。示例:
"This is the first sentence"
变为:
“这是
第一句话
我试过使用 \n
和 <br>
,但 none 有效。
我还能尝试什么?
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>
如果您将引用分配给段落 p
的 textContent
字段,它将呈现为纯文本。如果您改为使用 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>