2013-07-23 30 views
6

我需要找到可以在IE8以及真正的瀏覽器中工作的Jquery。我是全新的jQuery的,下面是我的代碼,在現代瀏覽器的工作原理:什麼使用,而不是Object.keys()?

$('#FIELD_'+office_id).on('change',function(){ 
    offices = $(this).val(); 
for(var i=0; i<=Object.keys(southland.address).length;i++){ 
     if(offices == Object.keys(southland.address)[i]){ 
      address = southland.address[offices]Object.keys(southland.address[offices])[0]]; 
     } 
    } 

其中southland.address來自外部陣列。這適用於Chrome,IE10和FF,我可以爲IE8做什麼?

+0

這段代碼在IE8中會發生什麼?它是否會拋出任何錯誤,或者它不會默默工作? –

+1

這個代碼的第5行有一個語法錯誤,靠近'offices] Object.keys' – DhruvPathak

+0

準確地說,它什麼也沒有。 –

回答

10

爲了支持Object.keys在舊的瀏覽器,你可以使用這個片段:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Compatibility

if (!Object.keys) { 
    Object.keys = (function() { 
    var hasOwnProperty = Object.prototype.hasOwnProperty, 
     hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), 
     dontEnums = [ 
      'toString', 
      'toLocaleString', 
      'valueOf', 
      'hasOwnProperty', 
      'isPrototypeOf', 
      'propertyIsEnumerable', 
      'constructor' 
     ], 
     dontEnumsLength = dontEnums.length; 

    return function (obj) { 
     if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object'); 

     var result = []; 

     for (var prop in obj) { 
     if (hasOwnProperty.call(obj, prop)) result.push(prop); 
     } 

     if (hasDontEnumBug) { 
     for (var i=0; i < dontEnumsLength; i++) { 
      if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]); 
     } 
     } 
     return result; 
    }; 
    })(); 
} 

或該填充工具(包括其他墊片,以及):

https://github.com/kriskowal/es5-shim/

+0

此代碼是否需要在特定位置進行?非常感謝。 –

+0

它應該出現在使用Object.keys的第一個實例的上方,但最好應該放在腳本的「polyfills」區域(您可以放置​​其他墊片/插件/實用程序等) –

+0

謝謝。 WordPress的情況下,您可以輕鬆地將它添加到您當前主題文件夾中的main.js。 – erm3nda