函数之间的全局变量"undefined"?

Global variable between functions "undefined"?

一定有更好的方法来做到这一点,但我正在使用 Magnific Popup 和 .onclick() 函数来附加弹出窗口,并将 ID 分配给 div。这是我的代码

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    
});

我正在尝试使用 magnificPopup 函数中的 class card-removecardID 附加到锚点。

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

感谢您的宝贵时间

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

each 中您可以访问元素实例

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

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

});

您可以使用 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>