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

时间:2019-02-08 04:01:40

标签: javascript jquery magnific-popup

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

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>

现在如何使用下面的类.popup-with-zoom-anim动态创建的标记?

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

2 个答案:

答案 0 :(得分:1)

您也可以使用delegate option

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

答案 1 :(得分:0)

我发现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');

});