如何使用 javascript 在 html 元素中创建新行

发布于 2025-01-18 11:09:15 字数 662 浏览 0 评论 0原文

我想在“ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救星 2025-01-25 11:09:17

因为您要在加载HTML之前尝试获取元素,因此日志变量是代码中的null

请尝试此代码。

<p id="log>hello</p>
window.onload = function init() {
  const log = document.getElementById("log");
  log.innerText = "\n first \n second";
};

Because you are trying to get element before loading HTML, so the log variable is null in your code.

Please try this code.

<p id="log>hello</p>
window.onload = function init() {
  const log = document.getElementById("log");
  log.innerText = "\n first \n second";
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文