javascript - Iterating over jQuery selector with variable, using closures -


[first time on stackoverflow.] trying dynamically add html buttons page , give them javascript function run when clicked, using jquery's click. want have 1 button each element in array, used loop. code looks (simplified)

for (var = 0; < results.length; i++) {     $("#" + place[i].place_id).click(function(){console.log("test");})             $("#" + place[i].place_id).click(); } 

(i inject buttons right id's in same loop.) code, when run, console logs "test" right number of times, afterwards, last button responds "test" when clicked. (this situation little absurd.) so, think event handler ends using final value of assign event handler. think problem has closures, not sure how make closure out of jquery selector (and in general not familiar them).

in contrast, hack solution, "manually" wrote code below right below , outside loop, , works expected, in clicking causes console log.

$("#" + place[0].place_id).click(function(){console.log("test");); $("#" + place[1].place_id).click(function(){console.log("test");}); etc. 

(of course, occurs within larger context - google maps places api call's callback.)

first, understanding problem correctly? second, work? should take different approach altogether, use .each()?

(i later want display property of place[i] when clicked, think need callback final hack code looks this:

$("#" + place[0].place_id).click(function(){google.maps.event.trigger(placemarkers[0], "click"); repeated 20 times 

to this, can create self executing function inside loop, this:

for (var = 0; < results.length; i++) {     (function(index) {         $("#" + place[index].place_id).click(function() {              //do place[index] here          });     })(i); } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -