即使使用Polyfill,IE也不支持.

Mar*_*all 11 javascript

我已将forEach polyfill添加到我的JavaScript文件的顶部,但Internet Explorer仍然说它不支持该功能.

我基本上想要遍历querySelector的结果,但是我在脚本中的其他一些数组对象上使用forEach.

这一切都适用于Chrome.

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

  Array.prototype.forEach = function(callback/*, thisArg*/) {

    var T, k;
    if (this === null) {
      throw new TypeError('this is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    if (arguments.length > 1) {
      T = arguments[1];
    }
    k = 0;
    while (k < len) {
      var kValue;
      if (k in O) {
        kValue = O[k];
        callback.call(T, kValue, k, O);
      }
      k++;
    }
  };
}

(function() {

  var instance = null,
      container;

  // Constructor
  this.MarvLightbox = function() {
    // Initialise plugin
    this.init();
  };

  // Initilise the plugin
  MarvLightbox.prototype.init = function() {

    document.querySelectorAll('[data-click]').forEach(function(e) {
      e.addEventListener('click', [clickevent]);
    });

  };

}());
Run Code Online (Sandbox Code Playgroud)

不应该添加polyfill修复IE的这个问题?

Fra*_*ijn 17

另一种使IE9 +支持的方法forEach:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <span class="demo">See me.</span>
    <span class="demo">See me.</span>
    <span class="demo">See me.</span>
    <span class="demo">See me.</span>
    <script>
        // Function to make IE9+ support forEach:
        if (window.NodeList && !NodeList.prototype.forEach) {
            NodeList.prototype.forEach = Array.prototype.forEach;
        }

        // Works with Nodelists (i.e. HTMLcollections):
        var demos = document.querySelectorAll('.demo');
        demos.forEach(function(item) {
            item.style.color = 'red';
        });

        // As well as with Arrays:
        var gherkins = ['gher1', 'gher2', 'gher3'];
        gherkins.forEach(function(item) {
            console.log(item);
        });
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在IE11中测试,根据其模拟功能,它也可以在10和9(不是8)中工作.

  • 我更喜欢这种解决方案,它避免了重写现有代码库的麻烦 (2认同)

chr*_*con 7

您正在向Array对象添加原型,并尝试在NodeList无法正常工作的对象(这是querySelectorAll返回而不是数组)上使用它。从节点列表中制作一个数组,或使用

Array.prototype.forEach.call(document.querySelectorAll('[data-click]'), function (e) {
    // your code
});
Run Code Online (Sandbox Code Playgroud)