2017-06-20 5 views
0

私はJavaScriptファイルの最上部にfor eachポリフィルを追加しましたが、Internet Explorerはまだその機能をサポートしていないと言っています。IE PolyfillでもforEachはサポートされません。

私は基本的に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]); 
    }); 

    }; 

}()); 

この問題をIEで修正しないでください。

+1

'querySelectorAll'は配列ではなく' NodeList'を返します。 –

+0

['Array.from'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from?v=control) – Emissary

+1

@Emissary非常に悪い提案 - それはES6ですIE – baao

答えて

2

Arrayオブジェクトにプロトタイプを追加していて、NodeList(これは配列の代わりにquerySelectorAllが返すものです)で使用しようとすると動作しません。配列をノードリストから外すか、または使用する

Array.prototype.forEach.call(document.querySelectorAll('[data-click]'), function (e) { 
    // your code 
}); 
+0

これは本当に役に立ちます。なぜpolyfillにこのようなサポートがないのか分かりません。 –

関連する問題