"JScript object expected" 在 IE8 中

"JScript object expected" in IE8

我正在尝试获取具有特定 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 object expected"。

有人知道该怎么做吗? (不使用 jquery)

谢谢。

如果需要向后兼容IE8,则不能使用querySelectorAll。您需要单独使用 getElementsByTagName 或 select 它们。

此外,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)));
});