我在 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 中不正常。
你能告诉我哪里出了问题吗?
最佳答案
IE doesn't support
remove()
native Javascript function but does supportremoveChild()
.
remove() 的浏览器兼容性
解决方案 n°1
在纯 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()
native 函数从其父节点中删除该元素。
解决方案 n°2
在包括 IE 在内的所有浏览器上以纯 JavaScript 形式使用 removeChild()
只需调用它代替 remove()
。
element.removeChild(child);
More info在 Mozilla 开发者网络上。
解决方案 n°3
使用 jQuery 通过 code.jquery.com CDN通过使用以下代码:
<!-- 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 库中,因此您可以在包含后调用它。
编码愉快! :-)
关于JavaScript remove() 在 IE 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428877/