当我单击复选框并单击列表中单个项目上的删除时,它会按预期删除。当我检查所有项目并单击删除它没有。我不知道为什么,我想知道。我理解为了在引用DOM元素索引时删除数组中的元素,首先必须获取DOM元素索引,但我现在对此不感兴趣。我真的不知道为什么这段代码不起作用,这让我觉得很蠢。
window.onload = function() {
let toDos = [
{ title: "MOM", complete: false }
,{ title: "DAD", complete: false }
,{ title: "The Universe", complete: false }
,{ title: "MOM", complete: false }
,{ title: "DAD", complete: false }
,{ title: "The Universe", complete: false}
];
const deleteButton = document.getElementsByTagName("button")[0];
var inputElems = document.querySelectorAll(".todo-delete");
deleteButton.addEventListener("click", function() {
inputElems = document.querySelectorAll(".todo-delete");
for (var i = 0; i < inputElems.length; i += 1) {
if (inputElems[i].checked) {
toDos = toDos.filter(function(val, index) {
if (index !== i) {
return val
}
});
}
}
inputElems = document.querySelectorAll(".todo-delete");
console.log(toDos);
renderDOM(toDos);
});
function renderDOM(toDos) {
const todoList = document.getElementById('todo-list');
todoList.textContent = '';
toDos.forEach(function(toDo) {
const newLi = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.className = "todo-delete";
checkbox.type = "checkbox";
newLi.textContent = toDo.title;
todoList.appendChild(newLi);
newLi.appendChild(checkbox);
});
}
renderDOM(toDos)
};
&#13;
<ul id="todo-list">
</ul>
<hr>
<button>delete</button>
&#13;
答案 0 :(得分:0)
问题是当你过滤toDos
数组时。在一次操作中过滤一半以上i
内容后,for循环索引toDos
变得比toDos
数组中的元素更多。
更改for (var i = 0; i < inputElems.length; i += 1) {
到for (var i = inputElems.length -1; i >= 0; i--)
这里我们改变循环方向从左到右我们从右到左,意味着每次迭代减少索引,所以当我们过滤掉1个元素时,我们也减少了i
。
答案 1 :(得分:0)
问题是您在每次删除后过滤数组并更改索引。在实际删除之前,您需要知道要删除的所有索引。
window.onload = function() {
let
toDos = [ {
title : "MOM",
complete : false
}, {
title : "DAD",
complete : false
}, {
title : "The Universe",
complete : false
}, {
title : "MOM",
complete : false
}, {
title : "DAD",
complete : false
}, {
title : "The Universe",
complete : false
} ];
const deleteButton = document.getElementsByTagName("button")[0];
var inputElems = document.querySelectorAll(".todo-delete");
deleteButton.addEventListener("click", function() {
inputElems = document.querySelectorAll(".todo-delete");
var removes = []; // added this part
for (var i = 0; i < inputElems.length; i += 1) {
if (inputElems[i].checked) {
removes.push(i); // added this part
}
}
toDos = toDos.filter(function(val, index) {
if (removes.indexOf(index) === -1) { // added this part
return val;
}
});
inputElems = document.querySelectorAll(".todo-delete");
renderDOM(toDos);
});
function renderDOM(toDos) {
const
todoList = document.getElementById('todo-list');
todoList.textContent = '';
toDos.forEach(function(toDo) {
const
newLi = document.createElement('li');
const
checkbox = document.createElement('input');
checkbox.className = "todo-delete";
checkbox.type = "checkbox";
newLi.textContent = toDo.title;
todoList.appendChild(newLi);
newLi.appendChild(checkbox);
});
}
renderDOM(toDos)
};