简体   繁体   中英

Javascript not executing on elements after ajax request

I have a table with some images, when the Ajax is called it removes the previous table and returns another table with new images.

$("img").click(function(){
    $.post("gallery.php", function(data){
        $("#left-gallery, #right-gallery").html("").append(data);
    });
});

This is how I get the information from the php file.

The problem is that the new elements does not trigger the click events that the previous ones use to.

If I clicked on an image in the table it should replace another image on the page outside the table.

$("#left-gallery img").click(function(){
    $("#left-gallery td").removeClass("highlighted");

    var source = $(this).attr("src");
    $("#image1-image").attr("src", source); //replaces a big image outside the table
    $(this).parents("td").addClass("highlighted");
});

The table images are nested like :

<tr>
    <td>
        <a  href = "image.jpg"> 
            <img src = "image.jpg">
            Image
        </a>
    </td>
</tr>

Even preventing the default behaviour does not work.

$("td a").click(function(e){
    e.preventDefault();
});

The javascript is after the <body> and is internal. I do not know how to get the click events or any to work on the returned table and any help would be appreciated.
Thank you.

use delegation because you are dynamically modifying the DOM

$('#left-gallery').on('click','img',function(){
        // your code here
})

By doing this, you attach the event handler to the #left-gallery element = which is static. It will then listen for click events from descendant images and handle them as they bubble up

Depending on which version of jQuery you are using

$('element').live('event',function({ code here..})); // jQuery 1.3+

$('staticparent').delegate('element', 'event', function(){ code here..}); // jQuery 1.4.3+

$('staticparent').on('event', 'element', function(){ code here.. }); // jQuery 1.7+

You were doing

$("#left-gallery img").click(function(){

Which binds the event handlers to the images.. The images no longer exist after you modified the dom.. and you never binding event handlers to the newly added images so thats why the clicking didn't do anything

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM