我不明白为什么会发生这种情况。我有一个嵌套在另一个滑动器中的滑动器(一个用于垂直滚动,另一个用于水平滚动。让我发疯的是,当我需要销毁它时,嵌套的滑动器没有定义。这是我正在做的:
function embedSwiper(){
var embeddedEcosystem = new Swiper('.swiper-nested', {
//Styling set in bootstrap.min.css for pagination
mode: 'vertical',
pagination: '.pagination-nested',
paginationClickable: true,
simulateTouch : true,
});
embeddedEcosystem.swipeTo(0, 500, false);
return embeddedEcosystem;
}
创建滑动器,并将其返回到此函数:
function reInitEmbedded(){
setTimeout(function(){
embed = embedSwiper();
$(".swiper-nested").css({"height" : "0px"});
$(".swiper-nested").css({"height" : $(".internal-relations").height()});
useLocalImg();
embed.reInit();
//Set the slide height properly since it never works as intended
return embed;
}, 600);
}
我需要在此处设置高度,否则幻灯片无法正确安装(是的,我已经尝试计算高度,但由于我使用工作灯,这在移动设备上给我带来了问题)
现在,事情变得不稳定了。我正在 Chrome 中对此进行测试(抱歉,目前我无法为您提供链接)。
//Resize cards
swiper = reinitSwiper();
innerSwiper = reInitEmbedded();
//Show info
detailsTransition();
//Hides the overlay, and empties the panels to be filled next time
//Bound calls for use when needed
$(".back-button.btn.btn-primary.pull-left").on('click', function(){
goBack(lookUpName);
innerSwiper.destroy();
swiper.destroy();
});
如您所见,我有 swiper
变量,它可以正常工作,并且可以正常销毁,并且我有innerSwiper。其余的都是无关紧要的,因为它在此之前就已经工作了。让我抓狂的是 innerSwiper
一直显示为 undefined
,但这不应该是因为我已经跟踪了 chrome 调试器中的堆栈调用和 返回
都具有内部 swiper 的 swiper 变量。所以我的问题是:我做错了什么,导致我一直未定义?
最佳答案
这是因为范围问题。
在单击处理程序内,范围发生更改,并且无法访问innerSwiper。因此,请执行以下操作:
this.swiper = reinitSwiper();
this.innerSwiper = reInitEmbedded();
var self = this; // HOLD REFERNECE TO THIS AS SELF
//Show info
detailsTransition();
//Hides the overlay, and empties the panels to be filled next time
//Bound calls for use when needed
$(".back-button.btn.btn-primary.pull-left").on('click', function(){
goBack(lookUpName);
self.innerSwiper.destroy(); // here you use self that has reference to swiper
self.swiper.destroy();
});
正如 Thom x 所指出的,还有一个错误。像这样修复它:
// Make sure self is defined be before this function
function reInitEmbedded(){
setTimeout(function(){
embed = embedSwiper();
$(".swiper-nested").css({"height" : "0px"});
$(".swiper-nested").css({"height" : $(".internal-relations").height()});
useLocalImg();
embed.reInit();
//Set the slide height properly since it never works as intended
self.innerSweeper = embed; // change this
}, 600);
}
关于javascript - 为什么我的刷卡器未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25021522/