JavaScript remove()在IE中不起作用 [英] JavaScript remove() doesn't work in IE

查看:585
本文介绍了JavaScript remove()在IE中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有以下代码:

I have the following code in JavaScript:

all_el_ul = document.getElementsByClassName('element_list')[0];
div_list = all_el_ul.getElementsByTagName("div");
for (i = 0; i < div_list.length; i += 1) {         
  div_list[i].remove();             
}

我知道这是问题所在,因为我使用了 alert('test'); 查看代码停止工作的位置。
一切都在FF,Chrome,Opera和其他工作,但不在IE中。

I know that this is the problem because I used alert('test'); to see where the code stops working. Everything is working in FF, Chrome, Opera and others but not in IE.

你能说出来是什么问题吗?

Could you please tell what is wrong?

推荐答案


IE不支持 remove()本机Javascript函数但是
支持 removeChild()

IE doesn't support remove() native Javascript function but does support removeChild().



删除浏览器兼容性()



Browser compatibility for remove()

使用删除() 在纯Javascript中,您可以自己声明,并使用以下代码:

Use remove() in pure Javascript you can declare it yourself with this following code :

// Create Element.remove() function if not exist
if (!('remove' in Element.prototype)) {
    Element.prototype.remove = function() {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
    };
}
// Call remove() according to your need
child.remove();

正如您所见,函数获取元素的父节点,然后从父节点中删除此元素 removeChild()原生函数。

As you can see the function get the parent node of element and then remove this element from his parent with removeChild() native function.

在所有浏览器上使用 removeChild() ,包括IE,只需将其命名为 remove()

element.removeChild(child);

更多信息

通过 code.jquery.com CDN 使用jQuery 使用以下代码:

Use jQuery through code.jquery.com CDN by using this following code :

<!-- Include jQuery -->
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<!-- Use remove() -->
<script>
child.remove();
</script>

该函数包含在jQuery库中,因此您可以在包含后调用它。

The function is included in the jQuery library so you can call it after inclusion.

快乐的编码! : - )

这篇关于JavaScript remove()在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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