[英]how to stop repeating a function in javascript once I try and rebuild an array?
我正在尝试学习 javascript 并想制作一个具有一些不同功能的待办事项列表。 我添加了一个删除按钮 dd 它可以成功运行,但是当我重建我的列表时,它也会显示上一个列表。 我将如何仅使用新项目重建列表。 我知道我错过了一些简单的东西。
这是代码。
let theList = ["one", "two", "three"]
const todoList = document.querySelector(".todo-list");
window.onload = build;
function build() {
const tbl = document.createElement("table");
for (let i = 0; i < theList.length; i++) {
const row = document.createElement("tr");
row.ind = i;
// checkbox
const checkboxHolder = document.createElement("td");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "checkbox";
checkbox.id = "completed";
checkboxHolder.appendChild(checkbox)
row.appendChild(checkboxHolder);
// list Item
const listItem = document.createElement("td");
listItem.innerHTML = theList[i];
row.appendChild(listItem);
// edit button
const editBtn = document.createElement("span");
editBtn.innerText = "Edit";
editBtn.style.padding = "5px";
row.appendChild(editBtn);
// delete button
const deleteBtn = document.createElement("span");
deleteBtn.innerText = "Delete";
deleteBtn.style.padding = "5px";
deleteBtn.addEventListener("click", function () {
var itemOut = theList.splice(i, 1);
build();
})
row.appendChild(deleteBtn);
tbl.appendChild(row);
}
todoList.appendChild(tbl)
}
此代码有效。 我所做的只是在构建 function 的顶部添加了一些内部 HTML。 为什么这行得通?
let theList = ["one", "two", "three"]
const todoList = document.querySelector(".todo-list");
window.onload = build;
function build() {
todoList.innerHTML = "<h2>Todays List</h2>";
const tbl = document.createElement("table");
for (let i = 0; i < theList.length; i++) {
const row = document.createElement("tr");
row.ind = i;
// checkbox
const checkboxHolder = document.createElement("td");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "checkbox";
checkbox.id = "completed";
checkboxHolder.appendChild(checkbox)
row.appendChild(checkboxHolder);
// list Item
const listItem = document.createElement("td");
listItem.innerHTML = theList[i];
row.appendChild(listItem);
// edit button
const editBtn = document.createElement("span");
editBtn.innerText = "Edit";
editBtn.style.padding = "5px";
row.appendChild(editBtn);
// delete button
const deleteBtn = document.createElement("span");
deleteBtn.innerText = "Delete";
deleteBtn.style.padding = "5px";
deleteBtn.addEventListener("click", function () {
var itemOut = theList.splice(i, 1);
build();
})
row.appendChild(deleteBtn);
tbl.appendChild(row);
}
todoList.appendChild(tbl)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.