我正在构建嵌套的注释。 我的AJAX脚本获得了一个注释列表,如下所示并扩展它们 -
if (xmlhttp.readyState == 4 || myOb.readyState == "complete") {
// EVAL
var comments = eval('(' + xmlhttp.responseText + ')');
// POPULATE
var comm = "<ul>";
for(i = 0; i < comments.length; i++) {
if(comments[i].replyto == 0) {
comm = comm + expand(property, comments, i);
}
}
comm = comm + "</ul>";
// DISPLAY
document.getElementById("comments").innerHTML = comm;
}
这里,expand
函数是递归的,似乎导致了麻烦 -
function expand(property, comments, k) {
var comm = "";
// PRINT MAIN COMMENTS
comm = comm + "<li>";
// print otherparent comment data
// replies
comm = comm + "<ul>";
for(i = 0; i < comments.length; i++) {
// is a reply?
if(comments[i].replyto == comments[k].id) {
comm = comm + expand(property, comments, i);
}
}
comm = comm + "</ul>";
comm = comm + "</li>";
return comm;
}
此脚本最终只给出了我的第一个comments
数组元素(带有相应的子注释)。但是,如果我删除递归的代码,我不会面临这个问题(我也不会
得到任何子评论)..
function expand(property, comments, k) {
var comm = "";
// PRINT MAIN COMMENTS
comm = comm + "<li>";
// print otherparent comment data
// replies
comm = comm + "<ul>";
/*
for(i = 0; i < comments.length; i++) {
// is a reply?
if(comments[i].replyto == comments[k].id) {
comm = comm + expand(property, comments, i);
}
}
*/
comm = comm + "</ul>";
comm = comm + "</li>";
return comm;
}
我在eval
函数中设置了两个警报,在expand
调用之前和之后各一个:
for(i = 0; i < comments.length; i++) {
if(comments[i].replyto == 0) {
alert(i);
comm = comm + expand(property, comments, i);
alert(i);
}
}
两者都给了我不同的i
值。我做错了什么?
由于
答案 0 :(得分:4)
你忘了把“i”变成一个局部变量:
for(var i = 0; i < comments.length; i++) {
非常重要。