I am building nested comments. My AJAX script gets a list of comments like follows and expands them -
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 =开发者_如何学C comm;
}
Here, the expand
function is recursive, and seems to be causing trouble -
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;
}
This script ends up giving my only the first comments
array element (with it's respective sub-comments). But if i remove the recursive bit of code, I don't face that problem (also, i don
t get any sub-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;
}
I set two alerts in the eval
function, one each before and after the expand
call:
for(i = 0; i < comments.length; i++) {
if(comments[i].replyto == 0) {
alert(i);
comm = comm + expand(property, comments, i);
alert(i);
}
}
Both gave me different values of i
. What am i doing wrong?
Thanks
You forgot to make "i" a local variable:
for(var i = 0; i < comments.length; i++) {
That's really important.
精彩评论