繁体   English   中英

从数组JavaScript删除

[英]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);
  }

}

https://jsfiddle.net/wt0fux3f/6/

你似乎很近。 您已从数组中删除了该元素,但未从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM