JavaScript remove() 在 IE 中不起作用 [英] JavaScript remove() doesn't work in 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 supportremoveChild()
.
remove() 的浏览器兼容性
在纯 Javascript 中使用 remove()
您可以使用以下代码自己声明:
// 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.
在包括 IE 在内的所有浏览器的纯 JavaScript 中使用 removeChild()
只需调用它代替 remove()
.
element.removeChild(child);
使用 jQuery 通过 code.jquery.com CDN 使用以下代码:
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屋!