javascript - Variable scope in anonymous function -


i'm trying populate array in javascript using anonymous function in jquery getjson() function follows.

$(document).ready(function() {      function link(url, title) {         this.url = url;         this.title = title;     }     var links = [];      $.getjson("http://reddit.com/r/programming/.json?jsonp=?", function(data) {         $.each(data.data.children, function(i, item) {             var title = item.data.title;             var url = item.data.url;              links.push(new link(url, title));         })     });      for(var i=0; i< links.length; i++) {         var output = "<a href='" + k + "'>" + links[k] + "</a>";         $('<p>' + link + '</p>').appendto('#content');     }  }); 

but, when hit loop, links array shows empty. what's going on here?

try :

    $(document).ready(function() {          function link(url, title) {             this.url = url;             this.title = title;         }          $.getjson("http://reddit.com/r/programming/.json?jsonp=?", function(data) {             var links = [];             $.each(data.data.children, function(i, item) {                 var title = item.data.title;                 var url = item.data.url;                  links.push(new link(url, title));             })             for(var i=0; i< links.length; i++) {                 var output = "<a href='" + k + "'>" + links[k] + "</a>";                 $('<p>' + link + '</p>').appendto('#content');             }         });       }); 

your loop executed before callback ;)


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -