我试图在单击按钮时在数组中添加数据,它也发生了,我正在使用数组循环来显示数组中页面上的数据,但是当数据添加到数组中时,页面上却没有数据。 更改未反映在页面上。
如果您有任何解决方案,请提供。提前致谢。
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>
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>