此代码有什么问题?
var divarray = [];
var articleHTML = [];
var absHTML;
var keyHTML;
var bodyHTML = [];
var i = 0;
divarray = document.getElementById("yui-main").getElementsByTagName("div");
for ( var j in divarray) {
if(divarray[i].className == "articleBody"){
articleHTML = divarray[i];
for( var k in articleHTML ){
bodyHTML[i] = '';
if(articleHTML[i].className == "issueMiniFeature"){continue;}
if(articleHTML[i].className == "abstract"){absHTML = articleHTML[i]; continue;}
if(articleHTML[i].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
bodyHTML[i] = articleHTML[i];
}
break;
}
i++;
}
我得到的错误是:
TypeError: Cannot read property 'className' of undefined
我正在使用谷歌浏览器。
答案 0 :(得分:3)
你正在使用一个非常奇怪的循环。
for (var j in array) {
// use array[i]
++ i
}
问题是.getElementsByTagName
不返回数组,而是返回类似数组的接口。例如:
>>> for (var j in document.getElementsByTagName('body')) console.log(j)
0
length
item
namedItem
因此,在for
/ in
循环中,i
将升至array.length + 2
而不是array.length - 1
。由于array[array.length + 2]
不存在,它将返回undefined
并在您尝试访问其属性时抛出错误。
只需使用
for (var i = 0, len = array.length; i < len; ++ i) {
...
}
有数组。
答案 1 :(得分:2)
您将articleHTML
初始化为数组,然后您显然将articleHTML
设置为HTMLElement(divarray[i]
),然后将其视为数组(articleHTML[i]
) - 这实际上是试图获取您从i
中取出的HTMLElement的divarray
属性,该属性不存在,然后您尝试获取此未定义值的className
。< / p>
答案 2 :(得分:1)
你的意思是:
var divarray = [];
var articleHTML = [];
var absHTML;
var keyHTML;
var bodyHTML = [];
var i = 0;
divarray = document.getElementById("yui-main").getElementsByTagName("div");
for ( var j in divarray) {
if(divarray[j].className == "articleBody"){
alert("found");
articleHTML = divarray[j];
break;
}
bodyHTML[i] = '';
if(divarray[j].className == "issueMiniFeature"){continue;}
if(divarray[j].className == "abstract"){absHTML = divarray[j]; continue;}
if(divarray[j].className == "journalKeywords"){keyHTML = divarray[j]; continue;}
bodyHTML[i] = divarray[j];
i++;
}