-1

单击元素时,我试图拼接一个数组。当我对新数组进行控制台记录时,它是不规则的,有时会删除错误的数组元素,并且永远不会删除最后一个索引。这里有人对此有很好的解释吗?

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')
});
4

1 回答 1

0

它有时会删除错误的数组元素

您面临的问题data-id是存储的是固定索引,但toDo数组是可变的。当你从数组中删除一个元素时,它后面的所有索引都变得无效。例如,当你.splice(0, 1), 那么你不能再做splice(2, 1)任何事情,因为数组只剩下两个项目。

最后一个索引永远不会被删除。

如果您首先单击最后一个元素,它会。


你可以做的是

  • 不从toDo数组中删除索引(并剪切整个数组),而只是将数组值设置为null; 或者
  • 不存储原始索引,而是要删除的值,并indexOf在每次删除元素时在当前数组中搜索它们(使用 )
于 2015-04-23T22:04:47.307 回答