After filtering content, jQuery does not work

Asked

Viewed 202 times

0

I made a code listing database items with PHP (using data-id for jQuery to "read" the click), but when filtering the items using Ajax, click stops working.

PHP

while ($furni = $furnis->fetch_assoc()) {
     echo '<img src="./web-gallery/images/furnis/small_' . $furni['image'] . '" data-id="'.$furni['id'].'" />';
}

jQuery (in full: http://pastebin.com/BvAz0CRr)

success: function (e) {
     $(".small_items").html('');
     for (var i = 0; i < e.array.length; i++) {
          $(".small_items").append('<img src="./web-gallery/images/furnis/small_' + e.array[i].image + '" data-id="' + e.array[i].id + '" />');
     }
}

Explaining better, I have another function using . click to get the data of the item and as I said, listed by PHP o . click works normally, but when it filters and lists by jQuery, the . click stops working

  • Have you tried using the .on instead of .click? Take a look in that question, maybe it’ll help you.

  • 1

    I was using the . on, but without separating the selector, thanks for the link! it worked :D

1 answer

1

Replaces this line:

$('.small_items img').on('click', function () {

for this:

$('.small_items').on('click', 'img', function () {

What’s happening is that images receive a oscultator when you run that line I mentioned above. But then you remove the content of .small_items with $(".small_items").html(''); and this removes the Event handlers (event headphones).

So you have to use delegation for the event receiver to be tied to .small_items that is always present on the page, and only at the moment of click it will check if it is an element img to trigger the event or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.