【问题标题】:The object doesn't manage forEach Properties该对象不管理 forEach 属性
【发布时间】:2018-06-06 08:22:00
【问题描述】:

我有一个使用 forEach 方法的脚本,该方法适用于某些 Firefox 浏览器,但从不适用于 IE11。

错误是:对象不管理 forEach 属性

var clearContent = function clearContent() {
  var allDistricts = document.querySelectorAll(".district");
  allDistricts.forEach(function(item) {
    item.style.display = "none";
  });
};

哦,我可以轻松替换 forEach 方法吗? 谢谢

【问题讨论】:

    标签: javascript arrays foreach


    【解决方案1】:

    使用简单的for循环:

     var clearContent = function clearContent() {
        var allDistricts = document.querySelectorAll('.district');
        for (var i=0; i<allDistricts.length; i++) {
          allDistricts[i].style.display = 'none';
        }
      };
    

    【讨论】:

    • 谢谢,确实问题不在于 forEach,而在于 querySelectorAll。
    【解决方案2】:

    NodeList.querySelectorAll 是一个新功能,在过时的浏览器上不受支持。 (querySelectorAll 返回NodeList

    MDN says 它首先在 Chrome 51 和 FF 50 上得到支持,而这两个版本才在几年前发布(当然,它在 2013 年发布的 IE 上根本不支持)。

    对于 polyfill,你可以使用这个:

    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);
        }
      };
    }
    

    【讨论】:

    • 如何解决错误The error is : The object doesn't manage forEach Properties 提到的bu OP?
    • 如果他使用 polyfill,他能够在NodeLists 上使用forEach
    • 感谢您的帮助:)
    猜你喜欢
    • 2021-01-04
    • 2020-09-03
    • 2018-03-03
    • 1970-01-01
    • 2023-03-22
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多