我正在创建待办事项列表应用程序。我创建了 newNode 并将其附加到父节点。我为 newNode 提供了一个删除按钮,其中包含一个从DOM中删除 newNode 的事件侦听器。 有时当我在应用程序运行时点击删除按钮时,待办事项项目节点将被删除(按照需要),其他时候什么也不会发生,它会给出 NodeFoundError:节点是找不到。即使我执行console.log(newNode),它也会打印出节点信息,但它会产生NodeFoundError?任何想法为什么?错误通常在我删除1来执行项目后发生,当我尝试删除其他项目时,会出错。
for(var i = 0; i < serverArray.length ; i++){
//Parent node I append newNode to
var node = document.getElementById("toDoList");
var todo2 = new todo(serverArray[i].name, serverArray[i].deadline, serverArray[i].rating, serverArray[i].id, serverArray[i].done);
myArray.push(todo2);
//create a new node with values of current to do item being added
var newNode = document.createElement("p");
newNode.setAttribute("id", todo2.id);
newNode.setAttribute("class", "todosection");
var descNode = document.createElement("p");
descNode.setAttribute("id","descr");
descNode.innerHTML = todo2.name;
var deadlineNode = document.createElement("p");
deadlineNode.setAttribute("id","dead");
deadlineNode.innerHTML = todo2.deadline;
var priorityNode = document.createElement("p");
priorityNode.setAttribute("id","prio");
priorityNode.innerHTML = todo2.rating;
//My newNode gets three nodes added to it as paragraphs for styling purposes
newNode.appendChild(descNode);
newNode.appendChild(deadlineNode);
newNode.appendChild(priorityNode);
//Create **DELETE** button with appopriate type and attributes
var removeToDo = document.createElement('input');
removeToDo.setAttribute('type', 'button');
removeToDo.setAttribute("value", "Delete");
removeToDo.setAttribute("id", id);
removeToDo.addEventListener('click', function(event) {
newNode.parentNode.removeChild(newNode);
for(var i = myArray.length - 1; i >= 0; i--) {
if(myArray[i].id == removeToDo.id) {
myArray.splice(i, 1);
}
}
}, false);//Add an event listener which when clicked deletes to do node
newNode.appendChild(removeToDo);//appends delete button to newNode
node.appendChild(newNode);
}