简体   繁体   中英

jQuery - click on a link dynamically generated by AJAX

I read many different posts about this matter but I can't solve my problem. I am trying to create a simple lightbox on dynamically generated content.

   $(document).ready(function() {
  $("body").on("click", "button", function() {
    $("button").removeClass("selected");
    $(this).addClass("selected");

    var flickrAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
    var animal = $(this).text();
    var flickrOptions = {
      tags : animal,
      format: "json"
    };
    var displayPhotos = function(data) {
      var photoHTML = "<ul>";
      $.each(data.items, function(i, photo) {
        photoHTML += '<li class="grid-25 tablet-grid-50">';
        photoHTML += '<a href="' + photo.link + '" class="image">';
        photoHTML += '<img src="' + photo.media.m + '" ></a></li>';
      });
      photoHTML += '</ul>';
      $('#photos').html(photoHTML);
    }
    $.getJSON(flickrAPI, flickrOptions, displayPhotos);

      var $overlay = $('<div id="overlay"></div>');
      var $image = $("<img>");
      var $caption = $("<p></p>");

      //An image to overlay
      $overlay.append($image);

      //A caption to overlay
      $overlay.append($caption);

      //Add overlay
      $("body").append($overlay);

      //Capture the click event on a link to an image
      $("#photos a").click(function(event){
        event.preventDefault();
        var imageLocation = $(this).attr("href");
        //Update overlay with the image linked in the link
        $image.attr("src", imageLocation);

        //Show the overlay.
        $overlay.show();

        //Get child's alt attribute and set caption
        var captionText = $(this).children("img").attr("alt");
        $caption.text(captionText);
      });

      //When overlay is clicked
      $overlay.click(function(){
        //Hide the overlay
        $overlay.hide();
      });
  });
});

Here is my complete code on jsfiddle

The click event after the AJAX call doesn't fire up. How can I solve this?

what it's happening its that you are adding the event before the DOM exists, what you should do its wait for the response to actually render all the event and the interface or replace this:

  $("#photos a").click(function(event){
  });

for

  $(document).on("click","#photos a",function(){

});

that way the event its gonna exist always... Its my guess... I'm not sure if $("#photos a") actually get the element you want to attach the event, but you got the idea of how you can add event to DOM elements that still dont exist on the DOM.

在此处输入图片说明

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