函数“undefined”之间的全局变量?

时间:2016-09-17 21:19:44

标签: jquery magnific-popup

必须有一种更好的方法,但我使用Magnific Popup和.onclick()函数来附加一个弹出窗口,并为div分配一个ID。这是我的代码

var cardID;

$('.popup-with-zoom-anim').click(function(){
    var cardID = jQuery(this).attr("id");
    console.log(cardID);
});

$('.popup-with-zoom-anim').magnificPopup({
    items: {
    src: $('<div id="small-dialog" class="white-popup zoom-anim-dialog mfp-hide"><h1>Delete card?</h1><p>Are you sure you want to delete this payment option? This operation cannot be undone.</p><a href="#" class="card-remove" id="' + cardID + '"><i class="fa fa-globe"></i>Yes</a><a href="#"><i class="fa fa-globe"></i>Cancel</a></div>'),
    type: 'inline'
},
        closeBtnInside: true    
});

我正在尝试将cardID附加到card-remove函数中的magnificPopup类的锚点。

我不想使用全局变量,但我尝试将magnificPopup函数放在onclick中,但它没有我想要的预期功能。

感谢您的时间

2 个答案:

答案 0 :(得分:1)

每当您需要传递给插件选项的特定元素数据时,最简单的方法是在each循环内部进行初始化....即使只存在一个这样的元素。

each内,您可以访问元素实例

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

     var cardID = this.id;
     $(this).magnificPopup({/* same options as in question*/ });     

});

答案 1 :(得分:1)

您可以使用elementParse event代替获取cardID:

$('.popup-with-zoom-anim').magnificPopup({
  items: {
    src: $('<div id="small-dialog" class="white-popup zoom-anim-dialog"><h1>Delete card?</h1><p>Are you sure you want to delete this payment option? This operation cannot be undone.</p><a href="#" class="card-remove" id="cardID"><i class="fa fa-globe"></i>Yes</a><a href="#"><i class="fa fa-globe"></i>Cancel</a></div>'),
    type: 'inline'
  },
  closeBtnInside: true,
  callbacks: {
    elementParse: function(item) {
      console.log(this.ev.attr('id'));
      item.src.find('a[class="card-remove"]').attr('id', this.ev.attr('id'));
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/dimsemenov/Magnific-Popup/master/dist/magnific-popup.css">
<script src="https://rawgit.com/dimsemenov/Magnific-Popup/master/dist/jquery.magnific-popup.min.js"></script>

<button type="button" id="myBtn" class="popup-with-zoom-anim">Open Magnific PopUp</button>