我试图获取具有特定ID的HTML页面的所有元素。这适用于Safari,Chrome和Firefox。
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 :(得分: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)));
});