I'm using a jquery script called magnific popup and I'm trying to access a variable I created in a callback function, inside another callback function but I can't work out how to do it. My code for the magnific init looks like this:
$('.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);
}
}
});
If I try and set $('.mfp-bg').addClass(communityClass);
or $('.mfp-bg').addClass(item.community);
I get a Uncaught ReferenceError: communityClass is not defined.
I can't apply a class to mfp-bg inside elementParse as that element hasn't been created yet.
I know that I can't use variables from different functions in javascript, but I'm a bit stuck at this point on how I can actually use the data-community attribute inside the resize callback, because it seems like I can only create the variable inside the elementParse callback?
Any help would be much appreciated, cheers.
答案 0 :(得分: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);
}
}
});
答案 1 :(得分:0)
我在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);
}
}
});