jquery - Capturing counter value in Javascript closure -


this question has answer here:

the following code creates 10 elements under <body id="container" />. when click on element, see alert value 10.

how can each alert show index of each element?

for (var = 0; < 10; ++i) {   var id = "#element_" + i;   $("#container").append('<p id="element_' + + '">foo</p>');   $(id).click(function (e) {     alert(i);   }); } 

need create private closure

for (var = 0; < 10; ++i) {     (function(idx){         var id = "#element_" + idx;         $("#container").append('<p id="element_' + idx + '">foo</p>');         $(id).click(function (e) {             alert(idx);         });     })(i) } 

demo: plunker


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -