如何使用 javascript 在 html 元素中创建新行
我想在“ P”元素中创建一个新线路。我也尝试过BR标签和\ n标签,但它并没有真正起作用。当我运行代码时,新行显示为行之间的空间。
<p id="log"></p>
let log = document.getElementById("log");
let string = `|line1\n|line2`;
let array1 = string.split("|");
let i = 0;
let x = 0;
log.addEventListener("click", () => {
document.addEventListener("keypress", type);
})
function type() {
log.textContent += array1[i].charAt(x);
x++;
if (x === array1[i].length) {
x = 0;
i++;
}
if (array1[i] === undefined) {
document.removeEventListener("keypress", type);
}
}
i want to create a new line in "p" element . I have tried br tag and \n tag as well, but it didn't really work . when i run the code the new line appears as a space between the lines.
<p id="log"></p>
let log = document.getElementById("log");
let string = `|line1\n|line2`;
let array1 = string.split("|");
let i = 0;
let x = 0;
log.addEventListener("click", () => {
document.addEventListener("keypress", type);
})
function type() {
log.textContent += array1[i].charAt(x);
x++;
if (x === array1[i].length) {
x = 0;
i++;
}
if (array1[i] === undefined) {
document.removeEventListener("keypress", type);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您要在加载HTML之前尝试获取元素,因此日志变量是代码中的
null
。请尝试此代码。
Because you are trying to get element before loading HTML, so the log variable is
null
in your code.Please try this code.