2011-06-22 4 views
1

Je construis des commentaires imbriqués. Mon script AJAX obtient une liste de commentaires comme suit et les développe -Appel récursif affectant les variables de la méthode parente?

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; 
    } 

Ici, la fonction expand est récursive et semble causer des problèmes -

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; 
} 

Ce script finit par donner mon seulement le premier élément de tableau comments (avec ses sous-commentaires respectifs). Mais si je supprime le bit récursive de code, je ne sont pas confrontés à ce problème (aussi, je ne t obtenir des sous-commentaires) ..

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; 
} 

Je mis deux alertes dans la fonction eval, un chacun avant et après l'appel expand:

 for(i = 0; i < comments.length; i++) {    
      if(comments[i].replyto == 0) { 
       alert(i); 
       comm = comm + expand(property, comments, i); 
       alert(i); 
      } 
     } 

deux m'a donné des valeurs différentes de i. Qu'est-ce que je fais mal?

Merci

Répondre

4

Vous avez oublié de faire "i" une variable locale:

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

C'est vraiment importante.

+0

facepalm. Correct. Je vous remercie :) – Bojack

Questions connexes