将 magnificPopup 添加到动态创建的元素

Add magnificPopup to dynamic created element

我使用下面的代码它会弹出我想要的内容

function init_magnificPopup()
{
    $('.popup-with-zoom-anim').magnificPopup({

        type: 'inline',

        fixedContentPos: false,
        fixedBgPos: true,

        overflowY: 'auto',

        closeBtnInside: true,
        preloader: false,

        midClick: true,
        removalDelay: 300,
        mainClass: 'my-mfp-zoom-in'
    });
}

$(document).ready(function() {
    init_magnificPopup();
});

HTML

<a class="btn btn-primary popup-with-zoom-anim" href="#dialog">dialog popup</a> 

<div id="dialog" class="zoom-anim-dialog mfp-hide">
popup content
</div>

现在如何使用 class .popup-with-zoom-anim 动态创建的标签?

var content_string +=  '<a class="popup-with-zoom-anim" href="#dialog">dynamic dialog popup</a>';
$( "body" ).html(content_string);

我发现 answer 使用 .on() 方法并将 .magnificPopup('open'); 链接到最后

$("body").on('click', '.popup-with-zoom-anim', function(){ 

     $(this).magnificPopup({

                type: 'inline',

                fixedContentPos: false,
                fixedBgPos: true,

                overflowY: 'auto',

                closeBtnInside: true,
                preloader: false,

                midClick: true,
                removalDelay: 300,
                mainClass: 'my-mfp-zoom-in'
            }).magnificPopup('open');

});

您也可以使用 delegate option:

$('body').magnificPopup({
    delegate: 'a.popup-with-zoom-anim',
    type: 'inline',
    ...
});