我有一个脚本,在单击按钮时显示一个随机句子。 我想在某些句子中添加换行符。示例:
“这是第一句话”
成为:
“这是
第一句话”
我尝试使用\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>
答案 0 :(得分:2)
如果您将引号分配给段落textContent
的{{1}}字段,它将被呈现为纯文本。如果改用p
,它将解析并呈现您提供的任何HTML。
请参阅示例。
innerHTML
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;
}