代码不起作用,无法读取属性“className”;未定义的
这段代码有什么问题?
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
我正在使用 Google Chrome。
What is wrong with this code?
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++;
}
The error I get is:
TypeError: Cannot read property 'className' of undefined
I am using Google Chrome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你正在使用一个非常奇怪的循环。
问题是
.getElementsByTagName
不返回数组,而是返回类似数组的接口。例如:因此,在
for
/in
循环中,i
将上升到array.length + 2
而不是array.length - 1
。由于 array[array.length + 2] 不存在,因此当您尝试访问它的属性时,它将返回 undefined 并抛出错误。总是
与数组一起使用。
You're using a very strange loop.
The problem is
.getElementsByTagName
doesn't return an array, but an array-like interface. For example:Therefore, in your
for
/in
loop,i
will go up toarray.length + 2
instead ofarray.length - 1
. Sincearray[array.length + 2]
does not exist, it will returnundefined
and throw the error when you try to access a property of it.Just always use
with arrays.
您将
articleHTML
初始化为数组,然后显然将articleHTML
设置为 HTMLElement (divarray[i]
),然后将其视为array (articleHTML[i]
) — 这实际上试图获取您从divarray
中提取的 HTMLElement 的i
属性,但它不会不存在,然后你尝试获取这个未定义值的className
。You initialize
articleHTML
as an array, then you're apparently settingarticleHTML
to an HTMLElement (divarray[i]
) but then treating it like an array (articleHTML[i]
) — this actually tries to get thei
property of the HTMLElement that you pulled out ofdivarray
, which doesn't exist, and then you try to get theclassName
of this undefined value.你的意思:
Did you mean: