javascript - jQuery text() inside .getJSON() -
this question has answer here:
- $getjson , loop issue 4 answers
i'm trying names pokemon api , putting div field in html, .text() function jquery doesn't seem place text html when put inside .getjson function. curious problem be? thanks.
<div class="container"> <div class="row"> <div class="col-sm-3" id="1"> <div id="name1"></div> </div> <div class="col-sm-3" id="2"> <div id="name2"></div> </div> <div class="col-sm-3" id="3"> <div id="name3"></div> </div> <div class="col-sm-3" id="4"> <div id="name4"></div> </div> </div> </div>
javascript code
$(document).ready(function() { /*works*/ for(var j = 1; j < 5; j++){ $("#name" + j).text("hello"); } /*doesn't work*/ for(var j = 1; j < 5; j++){ var webaddress2 = "http://pokeapi.co/api/v1/pokemon/" + j; $.getjson(webaddress2, function(data) { console.log("test"); $("#name" + j).text("some text"); }); } });
create closure inside loop. since getjson
asynchronous ,operation, loop finish it's execution without waiting getjson
finish it's each execution.
you need bind value of j
closure
$(document).ready(function() { (var j = 1; j < 5; j++) { (function(index) { var webaddress2 = "http://pokeapi.co/api/v1/pokemon/" + index; $.getjson(webaddress2, function(data) { console.log("test"); $("#name" + index).text("some text"); }); }(j)) } });
Comments
Post a Comment