-1
我試圖在單擊元素時拼接數組。當我console.log新數組它不規則,有時刪除錯誤的數組元素和最後一個索引將永遠不會被刪除。這裏有一個很好的解釋嗎?Javascript中的拼接數組是不規則的
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')
});
現在的問題是,爲什麼會'這一點。 getAttribute(「data-id」)'返回一個數組,而不是一個字符串? – adeneo
@ adeneo:'toDo'是數組,'shouldDelete'是一個整數字符串。 – Bergi
這是一個很好的問題,我不能回答,我是JS新手,仍然在學習。有關我應該如何解決這個問題的任何想法? – NinjaGrisen