问题
I have two photos, both have the class "foto". Under each photo i added a button which allows me to delete the photo.
However, i can still open the photo in the galery after removing a photo from the DOM, instead of 1 of 1 photos like expected, i still have 1 of 2 at the bottom right and i can still see the deleted photo within magnificPopup's galery. Is it still in the cache?
$(document).ready
(
function()
{
$('.foto').magnificPopup
(
{
type: 'image',
closeOnContentClick: false,
closeBtnInside: false,
mainClass: 'mfp-with-zoom mfp-img-mobile',
image:
{
verticalFit: true,
titleSrc: function(item)
{
return item.el.attr('title') + ' · <a class="image-source-link" href="'+item.el.attr('data-source')+'" target="_blank">image source</a>';
}
},
gallery:
{
enabled: true
},
zoom:
{
enabled: true,
duration: 300, // don't foget to change the duration also in CSS
opener: function(element)
{
return element.find('img');
}
}
}
);
}
);
Is magnificPopup not compatible with dynamic elements? Is there a way to reinitialize the function without reloading the whole page?
回答1:
Try this ;)
function initMagnificPopup(){
$('.foto').magnificPopup({
type: 'image',
closeOnContentClick: false,
closeBtnInside: false,
mainClass: 'mfp-with-zoom mfp-img-mobile',
image: {
verticalFit: true,
titleSrc: function(item) {
return item.el.attr('title') + ' · <a class="image-source-link" href="'+item.el.attr('data-source')+'" target="_blank">image source</a>';
}
},
gallery: {
enabled: true
},
zoom: {
enabled: true,
duration: 300, // don't foget to change the duration also in CSS
opener: function(element) {
return element.find('img');
}
}
});
}
$(function(){
initMagnificPopup();
/* add call this function whenever you delete an image. */
});
回答2:
I found a solution. I added the event listeners into a function, then i just call this function anytime when i need to reinitialise it.
function init_magnificPopup()
{
$('.foto').magnificPopup
(
{
type: 'image',
closeOnContentClick: false,
closeBtnInside: false,
mainClass: 'mfp-with-zoom mfp-img-mobile',
image:
{
verticalFit: true,
titleSrc: function(item)
{
return item.el.attr('title') + ' · <a class="image-source-link" href="'+item.el.attr('data-source')+'" target="_blank">image source</a>';
}
},
gallery:
{
enabled: true
},
zoom:
{
enabled: true,
duration: 300, // don't foget to change the duration also in CSS
opener: function(element)
{
return element.find('img');
}
}
}
);
}
$(document).ready
(
function()
{
init_magnificPopup();
}
);
So i just call init_magnificPopup()
at the end of my delete function. That works :)
回答3:
Try this with dynamic elements:
$(document).on('click', '.foto', function () {
$(this).magnificPopup({....});
});
来源:https://stackoverflow.com/questions/39144031/use-magnificpopup-with-dynamic-elements