为什么数组中的更改没有反映在页面中

问题描述 投票:0回答:1

我试图在单击按钮时在数组中添加数据,它也发生了,我正在使用数组循环来显示数组中页面上的数据,但是当数据添加到数组中时,页面上却没有数据。 更改未反映在页面上。

如果您有任何解决方案,请提供。提前致谢。

const ob = ["first", "second", "third"];

for (let i = 0; i < ob.length; i++) {
  const nametag = `<p>${ob[i]}</p>`;
  document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);
}
function add() {
  const value = document.querySelector("textarea").value;
  ob.push(value);
}
document.querySelector(".add").addEventListener("click", () => add());
<div class="name-list"></div>
<textarea placeholder="enter name"></textarea><br>
<button class="add">Add Name</button>

javascript arrays push
1个回答
0
投票

您必须更新 HTML 以在单击按钮时添加名称。您可以使用

insertAdjacentHTML()
来更新 DOM,如下所示:

const ob = ["first", "second", "third"];

for (let i = 0; i < ob.length; i++) {
  const nametag = `<p>${ob[i]}</p>`;
  document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);
}

function add() {
    const value = document.querySelector("textarea").value;

    //update the HTML for the newly added name
    const nametag = `<p>${value}</p>`;
    document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);

    //add the new name to the array
    ob.push(value);

    //clear the textarea for the next input
    document.querySelector("textarea").value = "";
  }

document.querySelector(".add").addEventListener("click", () => add());
<div class="name-list"></div>
<textarea placeholder="enter name"></textarea><br>
<button class="add">Add Name</button>

© www.soinside.com 2019 - 2024. All rights reserved.