1

I'm trying to add a click event handler for each element that was created from JSON dynamically.

Here is my code :

$.getJSON('slides.json', function (data) {
    for (var i = 0; i < data.length; i++) {
        var s = sym.getSymbol("Base").createChildSymbol("Frame", "Slider");
        s.$("Frame").css({
            "background-image": "url('" + data[i].image + "')"
        });
        s.$("Frame").click("click", function (e) {
            alert(data[i].title)
        });
        s.getSymbolElement().css({
            "position": "absolute",
            "right": i * 81 + 5 + "px"
        });
        sym.getSymbol("Base").$("Slider").css({
            "width": i * 81 + 5 + "px"
        });
    } //for
});

This code would create 5 Frame with their image dynamically from JSON file. I want to be able to click on them and alert the index of the clicked image.

But in the code above, when I click on any image it always alerts 5, i.e. just the last value of i.

I also tried to replace i with data[i].title but nothing happened, there is no access to the JSON file that can read information from that.

How can I solve this?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Parsoua
  • 43
  • 5
  • what is Frame? iFrame? XML, html5? – Ol Sen May 05 '13 at 14:03
  • possible duplicate of [Jquery add event handler](http://stackoverflow.com/questions/5772018/jquery-add-event-handler) – Felix Kling May 05 '13 at 14:09
  • Actually it's a duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/q/750486/218196). You really should read this question/answer, so that you understand the actual problem. – Felix Kling May 05 '13 at 14:14

2 Answers2

1

You can use jQuery .on api to attach event for dynamic contents.

this sample code will atach click event for all dynamically created div elements

$("body").on("click", "div", function(event){
  alert($(this).text());
});
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
1

That's because when the click event fires, the for-loop has already completed and the value of i remains 5. I don't think I fully understand what you're trying to do here, but you might try saving the title in the element and reloading it when the click event fires:

for ( var i=0; i < data.length; i++ ) {
    var s = sym.getSymbol("Base").createChildSymbol("Frame", "Slider");
    s.$("Frame").css({"background-image":"url('"+data[i].image+"')"});
    s.$("Frame").data('title', data[i].title);
    s.$("Frame").click("click", function(e){ alert($(this).data('title'))});
}
Antti Mäki
  • 108
  • 1
  • 8