【问题标题】:How can I make .querySelectorAll() or .forEach() work in Firefox?如何使 .querySelectorAll() 或 .forEach() 在 Firefox 中工作?
【发布时间】:2016-12-09 06:20:05
【问题描述】:

我想删除所有 sample 类的元素。

这在 Chrome 和 Safari 中运行良好:

document.querySelectorAll('.sample').forEach(function(e) {
    e.parentNode.removeChild(e);
});

这是我在 Firefox 中遇到的错误:

TypeError: document.querySelectorAll(...).forEach 不是函数

【问题讨论】:

  • document.querySelectorAll('.sample') 是否返回 Array

标签: javascript foreach


【解决方案1】:

document.querySelectorAll 返回一个像数组一样索引的 NodeList,但不是数组,因此您不能在其上调用数组方法。

您可以在 ES6 中使用 Array.from(nodeList) 或在 ES5 中使用 Array.prototype.slice.call(nodeList)

 Array.from(document.querySelectorAll('selector')).forEach(el => el)

【讨论】:

  • 他们在NodeList 上实现了forEach 方法,但它不是标准的,因此不应依赖。
  • 这有效:Array.from(document.querySelectorAll('.sample')).forEach(function(e) { e.parentNode.removeChild(e); });
  • 不幸的是,在前端开发中,我们只能在最差的浏览器支持的功能时尽可能快。 developer.mozilla.org/en/docs/Web/API/…
  • 谁能告诉我forEach(el => {}) && forEach(function(){})有什么区别
【解决方案2】:

我刚刚在 Firefox 71 中测试了 document.querySelectorAll('.element').forEach,并且成功了。

CanIUse 表明它在 FF 中得到支持,从版本 50(2016 年末)开始:https://caniuse.com/#search=forEach

旧版本的 FF 拥有 0.25% 的市场份额,因此 .forEach 应该可以安全使用。

【讨论】:

    【解决方案3】:

    您也可以使用 polyfill(参见 https://developer.mozilla.org/de/docs/Web/API/NodeList/forEach):

    if (window.NodeList && !NodeList.prototype.forEach) {
        NodeList.prototype.forEach = function (callback, thisArg) {
            thisArg = thisArg || window;
            for (var i = 0; i < this.length; i++) {
                callback.call(thisArg, this[i], i, this);
            }
        };
    }
    

    这会将 forEach 方法添加到 NodeList(如果缺少)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2017-06-07
      • 2017-06-07
      • 1970-01-01
      • 2018-06-30
      • 2010-10-13
      • 1970-01-01
      相关资源
      最近更新 更多