2017-02-20 26 views
0

我想要獲取具有特定ID的HTML頁面的所有元素。這適用於Safari,Chrome和Firefox。IE8中的「預期的JScript對象」

var value_fields_value = []; 
 
    var value_fields_alert = []; 
 
    var Variables = []; 
 
    var e; 
 

 
    
 
    value_fields_value = Array.prototype.slice.call(document.querySelectorAll('[id^=value_]')); 
 
    for(var i in value_fields_value){ 
 
     Variables.push(new Element(value_fields_value[i], new Adresse(value_fields_value[i].id.toString().replace('value_', ''), null, null, null, null))); 
 
    }

這應該在Internet Explorer上工作過,但我得到錯誤信息 「預期的JScript對象」。

有沒有人有想法該怎麼辦? (不使用jquery)

謝謝。

+0

的[IE8不支持querySelectorAll]可能的複製(http://stackoverflow.com/questions/16920365/ie8-does-not-support- queryselectorall) –

回答

0

如果您需要向後兼容IE8,則不能使用querySelectorAll。您需要使用getElementsByTagName或單獨選擇它們。

另外,for/in循環用於遍歷對象中的所有屬性,您有一個要循環訪問的數組。該代碼應該是這樣的:

var value_fields_alert = []; 
 
var Variables = []; 
 
var e; 
 

 
// No need to pre-declare this to an empty array when you are just going 
 
// to initialize it to an array anyway 
 
var value_fields_value = Array.prototype.slice.call(document.querySelectorAll('[id^=value_]')); 
 

 
// You can loop through an array in many ways, but the most traditional and backwards compatible 
 
// is a simply for counting loop: 
 
for(var i = 0; i < value_fields_value.length; ++i){ 
 
    Variables.push(new Element(value_fields_value[i], new Adresse(value_fields_value[i].id.toString().replace('value_', ''), null, null, null, null))); 
 
} 
 

 
// Or, you can use the more modern approach: 
 

 
// The Array.prototype.forEach() method is for looping through array elements 
 
// It takes a function as an argument and that function will be executed for 
 
// each element in the array. That function will automatically be passed 3 arguments 
 
// that represent the element being iterated, the index of the element and the array itself 
 
value_fields_value.forEach(function(el, in, ar){ 
 
    Variables.push(new Element(el, new Adresse(el.id.toString().replace('value_', ''), null, null, null, null))); 
 
});

相關問題