【问题标题】:Accessing js variable inside a separate callback (function)在单独的回调(函数)中访问 js 变量
【发布时间】:2015-07-29 01:25:44
【问题描述】:

我正在使用一个名为 magnific popup 的 jquery 脚本,我正在尝试访问我在回调函数中创建的变量,在另一个回调函数中,但我不知道该怎么做。我的 magnific init 代码如下所示:

$('.packery').magnificPopup({
    delegate: '.js-modal',
    type: 'ajax',
    mainClass: 'mfp-zoom-in',
    removalDelay: 500, //delay removal by X to allow out-animation
    callbacks: {
        elementParse: function(item) {
            item.community = item.el.attr('data-community');
            var communityClass = item.community;
            console.log(item.community);
            // this ^ does actually print the data-community 
            console.log('Parsing content. Item object that is being parsed:', item);
        },
        resize: function() {
            console.log('Popup resized');
            // resize event triggers only when height is changed or layout forced

            $('.mfp-bg').addClass(communityClass);
        }
    }
});

如果我尝试设置 $('.mfp-bg').addClass(communityClass);$('.mfp-bg').addClass(item.community);,我会收到未捕获的 ReferenceError:communityClass 未定义。

我无法在 elementParse 中将类应用于 mfp-bg,因为该元素尚未创建。

我知道我不能在 javascript 中使用来自不同函数的变量,但我对如何在 resize 回调中实际使用 data-community 属性有点困惑,因为我似乎可以只在 elementParse 回调中创建变量?

任何帮助将不胜感激,干杯。

【问题讨论】:

  • var communityClass; 高于一切,然后communityClass = item.community; 将位于两个函数都可以访问的范围内。

标签: javascript jquery magnific-popup


【解决方案1】:

您可以在函数外部创建一个全局变量并将item.community 分配给它。这样你也可以在其他回调中访问它

例如:

var communityClass;
$('.packery').magnificPopup({
delegate: '.js-modal',
type: 'ajax',
mainClass: 'mfp-zoom-in',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
    elementParse: function(item) {
        item.community = item.el.attr('data-community');
        communityClass = item.community;
        console.log(item.community);
        // this ^ does actually print the data-community 
        console.log('Parsing content. Item object that is being parsed:', item);
    },
    resize: function() {
        console.log('Popup resized');
        // resize event triggers only when height is changed or layout forced

        $('.mfp-bg').addClass(communityClass);
    }
}
});

【讨论】:

  • 谢谢,我刚试过这段代码,效果很好。我最终使用了一个预先存在的this.currItem 属性,但这对将来很有用,我至少现在对范围和变量有了更多的了解!
【解决方案2】:

我在 console.logging 之后意识到已经有一个我可以访问的 currItem 位,所以我将代码更改为这个,现在它可以正常工作了。

$('.packery').magnificPopup({
    delegate: '.js-modal',
    type: 'ajax',
    mainClass: 'mfp-zoom-in',
    removalDelay: 500, //delay removal by X to allow out-animation
    callbacks: {
        elementParse: function(item) {
            item.community = item.el.attr('data-community');
        },
        resize: function() {
            $('.mfp-bg').addClass(this.currItem.community);
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多