-2

Why the click function don't execute?

I put the click function after load the json, i try many times but i don't know why don't work (first time asking)

var contentJson = function () {
        $.getJSON("debacco.json", function (json) {
            $.each(json.ambientes.espressione.produtos, function (e, f, y, c) {
                $('.list-cubas-espressione').append('<li class="cuba-img" data-cuba="' + f.img + '"><img src="/images/espressione/produtos/' + f.img + '/' + f.img + '.jpg" /></li>');
            });
            $.each(json.ambientes.funzionale.produtos, function (e, f) {
                $('.list-cubas-funzionale').append('<li class="cuba-img" data-cuba="' + f.img + '"><img src="/images/funzionale/produtos/' + f.img + '/' + f.img + '.jpg" /></li>');
            });
            $.each(json.ambientes.gourmet.produtos, function (e, f) {
                $('.list-cubas-gourmet').append('<li class="cuba-img" data-cuba="' + f.img + '"><img src="/images/gourmet/produtos/' + f.img + '/' + f.img + '.jpg" /></li>');

            });
        });
}

contentJson();

$('.cuba-img').on('click', function () {
       alert('teste');
       imgCuba = $(this).attr('data-cuba');
       changeUrl();
       $('.cuba').css('background', "url(images/" + ambiente + "/produtos/" + imgCuba + "/" + imgCuba + ".jpg)");
});
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • 1
    possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – emerson.marini Aug 06 '14 at 12:25

2 Answers2

1

Because it's generated at runtime, so try using event delegation!

$('.list-cubas-funzionale').on('click','.cuba-img', function () {
    // Rest of the code
})
Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
0

Because AJAX (and getJSON) runs asynchronously. Your click handlers get binded before the elements exist. Use delegation or bind the events within an ajax callback.

$('.list-cubas-funzionale').on('click', '.cuba-img', function () {
       alert('teste');
       imgCuba = $(this).attr('data-cuba');
       changeUrl();
       $('.cuba').css('background', "url(images/" + ambiente + "/produtos/" + imgCuba + "/" + imgCuba + ".jpg)");
});
Alex
  • 9,911
  • 5
  • 33
  • 52