2011-06-22 36 views
1

我正在構建嵌套註釋。 我的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不同的值。我究竟做錯了什麼?

感謝

回答

4

你忘了把 「我」 一個局部變量:

for(var i = 0; i < comments.length; i++) {    

這是真的重要

+0

facepalm。正確。謝謝 : ) – Bojack