JavaScript remove() 在 IE 中不起作用

标签 javascript internet-explorer

我在 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 support removeChild().

remove() 的浏览器兼容性

Desktop browser compatipility for remove() function

Mobile browser compatipility for remove() function

解决方案 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/

相关文章:

css - 如果我在 IE 中重复一个 CSS 样式会怎样?

javascript - 如何使用大量编码日志调试 Rollup 构建输出?

JavaScript 原型(prototype)不被复制

javascript - 拉拉维尔 : How to show dependent variable on tab

javascript - 无法在 Internet Explorer 中检索资源

java - 如何避免页面重定向时 Internet Explorer 出现黑屏或白屏?

javascript - 如何在 React Native 中将褪色背景添加到堆栈图表

javascript - 部署我的 meteor 应用程序时出现问题

javascript - Internet Explorer 与我网站上的版本的兼容性

javascript - IE11 出现错误 "SCRIPT 1028 Expected identifier, string or number"