2

The following code creates 10 elements under <body id="container" />. When i click on any element, I always see an alert with the value 10.

How can I get each alert to show the index of each element?

for (var i = 0; i < 10; ++i) {
  var id = "#element_" + i;
  $("#container").append('<p id="element_' + i + '">foo</p>');
  $(id).click(function (e) {
    alert(i);
  });
}
shyam
  • 9,134
  • 4
  • 29
  • 44
necromancer
  • 23,916
  • 22
  • 68
  • 115

3 Answers3

4

You need either closure or simply use $.on() with data:

for (var i = 0; i < 10; ++i) {
  var id = "#element_" + i;
  $("#container").append('<p id="element_' + i + '">foo</p>');
  $(id).on("click", i, function (e) { alert(e.data); });
}
c-smile
  • 26,734
  • 7
  • 59
  • 86
  • Alternatively, you can do `.on()` first and then `.appendTo()` while caching `$('#container')`. – Ja͢ck Aug 26 '13 at 06:29
3

Don't make functions inside for loops

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

$("#container > p").click(function (e) {
    var idNum = this.id.split('_')[1];
    alert(idNum); // 0, 1, 2 ...
});

DEMO

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
2

need to create a private closure

for (var i = 0; i < 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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • we at SO is improving at how to downvote an answer simply because somebody doesn't like an answer.... where as the [down-vote](http://stackoverflow.com/help/privileges/vote-down) says `Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect` – Arun P Johny Aug 26 '13 at 06:20
  • Not my dv, but the title of the down-vote button says "This answer is not useful" :) – Ja͢ck Aug 26 '13 at 06:31
  • @Jack how is it not useful? it is a working solution... may not be the best one – Arun P Johny Aug 26 '13 at 06:33
  • It solves the problem, that's not my point; the tooltip of the actual button has that content, which is substantially different from the faq/help content. – Ja͢ck Aug 26 '13 at 06:34
  • @Jack that I understood... still if a person has to downvote he/she need to find the answer as `not useful` right... my question is how he/she might has found it as not useful – Arun P Johny Aug 26 '13 at 06:36
  • Well, in this case, I wouldn't know why someone would feel it's not useful; maybe they expected more explanation? – Ja͢ck Aug 26 '13 at 06:37
  • @Jack might be... I didn't give much explanation because OP used the term closure... thought the OP will understand it – Arun P Johny Aug 26 '13 at 06:38
  • @Jack this was useful. usually people do explain why not useful. – necromancer Aug 26 '13 at 08:04