[英]Deleting from array javascript
我正在遍歷數組並將其顯示在屏幕上。 不過,我有一個問題。 我試圖添加一個功能,當您單擊文本時,它會刪除該單擊的文本。 這是我的代碼:
var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];
for(let i = 0; i < array.length; i++){
var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);
p.onclick = function(){
array.splice(array[i], 1);
console.log(array);
}
}
當我單擊它時,它將從陣列中刪除該項目並將其記錄到控制台。 但它不會顯示在屏幕上。 有什么幫助嗎?
謝謝你,抓貓
干得好:
var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];
for (let i = 0; i < array.length; i++) {
let p = document.createElement('p'); //note the block scoping
p.textContent = array[i];
div.appendChild(p);
p.onclick = function() {
array.splice(array.indexOf(this), 1); //splice wants an index...
this.remove(); //remove el from document tree
console.log(array);
}
}
你似乎很近。 您已從數組中刪除了該元素,但未從DOM中刪除了這,這就是為什么您無法在html中看到更新的原因。
for(let i = 0; i < array.length; i++){
var p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);
p.onclick = function(){
array.splice(i, 1);
this.remove();//also remove from the DOM
console.log(array);
}
}
for(let i = 0; i < array.length; i++){
let p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);
p.onclick = function(){
array.splice(i, 1);//splice wants an index...
p.remove();//remove el from document tree
console.log(array);
}
}
您可能還想刪除html元素?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.