单击元素时,我试图拼接一个数组。当我对新数组进行控制台记录时,它是不规则的,有时会删除错误的数组元素,并且永远不会删除最后一个索引。这里有人对此有很好的解释吗?
var container = document.getElementById('container'),
notDone = document.getElementsByClassName('notDone'),
deleting = document.getElementsByClassName('delete'),
div,
remove,
i,
toDo = [
'One',
'Two',
'öäå'],
for(i = 0; i < toDo.length; i++){
div = document.createElement('div');
div.innerHTML = toDo[i];
div.className = 'notDone';
remove = document.createElement('div');
remove.innerHTML = '<p>Remove</p>';
remove.setAttribute("data-id", i);
remove.className = 'delete';
container.appendChild(div);
div.appendChild(remove);
notDone[i].addEventListener('click', function(){
if(this.classList.contains('notDone')){
this.className = 'done';
}else{
this.className = 'notDone';
}
});
deleting[i].addEventListener('click', function(event){
event.stopPropagation();
var shouldDelete = this.getAttribute("data-id");
console.log('va' + shouldDelete);
toDo.splice(shouldDelete, 1);
this.parentNode.remove();
console.log(toDo);
});
}
var check = document.getElementById('check');
check.addEventListener('click', function(){
console.log(toDo + ' checking array')
});