【问题标题】:"JScript object expected" in IE8IE8 中的“预期 JScript 对象”
【发布时间】:2017-02-20 15:25:20
【问题描述】:

我正在尝试获取具有特定 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)

谢谢。

【问题讨论】:

标签: javascript html internet-explorer-8


【解决方案1】:

如果需要向后兼容 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)));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多