Jquery - .forEach()在IE8中不起作用

Mil*_*o-J 27 html javascript jquery internet-explorer-8

我为其中一个平台创建了这个小小的交互 - http://jsfiddle.net/S79qp/426/

除IE8外,它在所有浏览器中都能正常工作.当我运行控制台时,似乎是这部分它有问题......

Array.prototype.forEach.call(l, function(item) {
        a.push(jQuery(item).text());
   });
Run Code Online (Sandbox Code Playgroud)

有人可以给我看一个IE8友好的替代品,所以我可以使它兼容所需的版本?

Cha*_*ock 44

如果你想要的只是forEach()在IE8中:

if (typeof Array.prototype.forEach != 'function') {
    Array.prototype.forEach = function(callback){
      for (var i = 0; i < this.length; i++){
        callback.apply(this, [this[i], i, this]);
      }
    };
}
Run Code Online (Sandbox Code Playgroud)

这将在任何没有内置的浏览器中按预期运行.

  • 在进入大型项目时,将其投票赞成,有时更容易,更安全地帮助纠正错误的浏览器,而不是尝试纠正实际上没有错误的代码 (4认同)

Guf*_*ffa 37

使用jQuery.each方法:

jQuery.each(l, function(index, item){
  a.push(jQuery(item).text());
});
Run Code Online (Sandbox Code Playgroud)

如果目标数组从开始为空,则可以使用此jQuery.map方法:

var a = jQuery.map(l, function(item){
  return jQuery(item).text();
});
Run Code Online (Sandbox Code Playgroud)