jQuery iDangerous Swiper,后续的 destroy() 和 reInit() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24715793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iDangerous Swiper, subsequent destroy() and reInit() methods
提问by monastic
According to the directions provided as an answer here...
根据此处作为答案提供的说明...
iDangerous Swiper plugin reset slides
I'm trying to do something like this:
我正在尝试做这样的事情:
http://jsfiddle.net/monastic/ydKn2/17/
http://jsfiddle.net/monastic/ydKn2/17/
<div id="slide-repo">
<div class="swiper-slide">
<img src="http://dummyimage.com/100x100/000/fff.jpg" />
</div>
...................
</div>
<div>
<button id="update-slides">Update Slides</button>
</div>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<img src="http://dummyimage.com/100x100/ff0000/fff.jpg" />
</div>
.................
</div>
</div>
var mySwiper = new Swiper('.swiper-container', {
mode: 'vertical',
loop: true,
loopAdditionalSlides: 5,
centeredSlides: true,
slidesPerView: 2,
initialSlide: 0,
});
$('button#update-slides').on('click', function(){
var swiperWrapper = $('.swiper-wrapper'),
newSlides = $('#slide-repo').children('.swiper-slide').clone(true);
mySwiper.destroy();
swiperWrapper.empty().append(newSlides);
$('.swiper-wrapper').attr('style', '');
mySwiper.reInit();
});
But console is returning 'Cannot read property 'init' of null'.
但是控制台正在返回“无法读取 null 的属性 'init'”。
Any suggestions?
有什么建议?
回答by cjspurgeon
I believe this is because you're calling mySwiper.destroy()
and therefore can't run reInit()
. The documentation says reInit is for resetting when you've added or removed slides. But here you're calling reInit on an element that is no longer a swiper.
我相信这是因为您正在调用mySwiper.destroy()
,因此无法运行reInit()
。文档说 reInit 用于在您添加或删除幻灯片时进行重置。但是在这里,您在不再是 swiper 的元素上调用 reInit。
Instead, you could re-create the swiper each time. (I'm not sure why just calling removeAllSlides
then reInit
does not keep the same settings.)
相反,您可以每次都重新创建 swiper。(我不确定为什么只是调用removeAllSlides
thenreInit
不会保持相同的设置。)
var settings = {
mode: 'vertical',
loop: true,
loopAdditionalSlides: 5,
centeredSlides: true,
slidesPerView: 2,
initialSlide: 0,
},
mySwiper = new Swiper('.swiper-container', settings);
$('button#update-slides').on('click', function(){
var swiperWrapper = $('.swiper-wrapper'),
newSlides = $('#slide-repo').children('.swiper-slide').clone(true);
mySwiper.destroy();
swiperWrapper.empty().append(newSlides);
$('.swiper-wrapper').attr('style', '');
mySwiper = new Swiper('.swiper-container', settings);
});
Fiddle: http://jsfiddle.net/L2HJK/2/