2013-02-12 79 views
2

我如何编写以下支持所有浏览器的代码? 因为它似乎是的foreach功能在IE8支持...Javascript ForEach Function无法在IE浏览器中工作

digits.forEach(function(value, index) { 
    // create a span with initial conditions 
    var span = $('<span>', { 
     'class': 'digit0', 
     'data': { 
      'current': 0, 
      'goal' : value 
     } 
    }); 
    // append span to the div#number 
    span.appendTo($('div#number')); 
    // call countUp after interval multiplied by the index of this span 
    setTimeout(function() { countUp.call(span); }, index * interval); 
}); 

看到完整的代码在这里http://jsfiddle.net/bBadM/(it's并不适用于所有浏览器中工作) 在此先感谢。

问候,

+0

Internet Explorer不支持“对每个”循环。您需要更改代码才能使用常规循环: – Rinku 2013-02-12 07:20:40

+0

您可以使用纯JavaScript进行循环,而jQuery将终止对IE8等旧浏览器的支持 – 2013-02-12 07:21:16

+4

由于您已经使用jQuery,请使用['$ .each()' ](http://api.jquery.com/jQuery.each/)。 – JJJ 2013-02-12 07:21:25

回答

9

MDN documentation for forEach包括实现早期版本的JS的浏览器所使用的方法的两种实现方法。

我将重现快速之一(见链接的完整的)位置:

if (!Array.prototype.forEach) { 
  Array.prototype.forEach = function(fn, scope) { 
    for(var i = 0, len = this.length; i < len; ++i) { 
      fn.call(scope, this[i], i, this); 
    } 
  } 
} 
相关问题