问题
I am loading a gallery onto a page using the Instagram API. The AJAX looks something like this
$.ajax ({
type: 'GET',
dataType: 'jsonp',
cache: false,
url: 'https://api.instagram.com/v1/tags/food/media/recent?client_id='+instagramCID,
success: function(data) {
for (i in data.data) {
$('.instagram').append('<div class="instagram-placeholder"><a href="' + data.data[i].images.standard_resolution.url + '" title="Photo via '+ data.data[i].user.username +' on Instagram" rel="lightbox[gallery]"><img class="instagram-image" src="' + data.data[i].images.thumbnail.url +'"/></a></div>');
}
}
});
The HTML renders something like this after the AJAX has loaded the content to the page:
<a href="http://distilleryimage1.instagram.com/5184cfc4754211e181bd12313817987b_7.jpg"
title="Photo via washingtonwoman on Instagram" rel="lightbox[gallery]"><img
class="instagram-image"
src="http://distilleryimage1.instagram.com/5184cfc4754211e181bd12313817987b_5.jpg"></a>
I know I need to load lightbox after the dynamic content is added to the page, but can't seem to figure out how to do that. All the other advice I've tried from stackoverflow has created crazy recursiveness that has crashed my browser.
Using this jquery lightbox plugin: http://leandrovieira.com/projects/jquery/lightbox/
回答1:
Does something like this work?
$.ajax ({
type: 'GET',
dataType: 'jsonp',
cache: false,
url: 'https://api.instagram.com/v1/tags/food/media/recent?client_id='+instagramCID,
success: function(data) {
for (i in data.data) {
$('.instagram').append('<div class="instagram-placeholder"><a href="' + data.data[i].images.standard_resolution.url + '" title="Photo via '+ data.data[i].user.username +' on Instagram" rel="lightbox[gallery]"><img class="instagram-image" src="' + data.data[i].images.thumbnail.url +'"/></a></div>');
}
//Re-initialise lightboxes
$('.instagram').lightBox();
}
});
You will need to pass the same configuration to the lightBox() function as you used to initially set up the lightbox when the page loaded.
Basically, what is going on here is that we're forcing the lightbox to re-initialise after the ajax content has loaded.
The above should be the simplest solution given the code that I have seen.
If you want to play around a bit more with ajax events, you may want to try binding on an ajax event instead, but that's a little outside the scope of this question.
来源:https://stackoverflow.com/questions/9849394/how-to-add-jquery-lightbox-to-content-added-to-page-via-ajax