Javascript删除不删除所有元素 [英] Javascript remove not removing all elements

查看:38
本文介绍了Javascript删除不删除所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考 fiddle - http://jsfiddle.net/fkwwyvz8/

Please refer fiddle - http://jsfiddle.net/fkwwyvz8/

x = document.getElementsByClassName("buddy_blocks");
for(i=0;i<x.length;i++)
    x[i].remove();

点击最后​​一个按钮,它必须删除所有其他按钮,但它没有并且只删除了其中的一些,不知道为什么?有什么方法可以删除所有这些按钮?

Click on the last button, and it had to remove all the other buttons, but it does not and only removes some of them, not sure why? And any way to remove all those buttons?

推荐答案

由于您的代码中似乎已经包含 jQuery,您可以使用它来删除所有按钮:

Since you appear to have jQuery in your code already, you can just use this to remove all buttons:

$(".buddy_blocks").remove();

<小时>

您的尝试无效,原因有两个:


Your attempt was not working for two reasons:

  1. document.getElementsByClassName() 返回一个动态 nodeList,每次删除元素时都会在您的下方更改,这会导致您在迭代中丢失元素
  2. 因为 DOM 元素没有 .remove() 方法(无论如何在大多数浏览器中 - 这是一种建议的方法,但尚未广泛使用).父级有一个 .removeChild() 你可以使用的方法.
  1. document.getElementsByClassName() returns a dynamic nodeList that changes underneath you each time you remove an element which causes you to miss elements in your iteration
  2. Because a DOM element does not have a .remove() method (in most browsers anyway - it is a proposed method, but isn't widely available yet). The parent has a .removeChild() method you can use instead.

<小时>

在纯 Javascript 中,您可以向后设置迭代,以便当您删除元素并导致动态 HTMLCollection 更改时,它不会弄乱您的迭代,因为更改将是您已经通过的元素.并且,切换到使用 .removeChild() 像这样:

function f() {
    var x = document.getElementsByClassName("buddy_blocks");
    for(var i = x.length - 1; i >= 0; i--) {
        x[i].parentNode.removeChild(x[i]);
    }
}

另外,请在所有函数局部变量上使用 var,这样你就不会创建偶然的全局变量",这会导致在某些时候难以找出错误未来.

Also, please use var on all variables that are intended to be local to your function so you are not creating "accidental global variables" which will cause hard to figure out bugs at some time in the future.

这篇关于Javascript删除不删除所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆