我有一个带有多个滑块的简单页面。每个滑块由三个幻灯片组成:左、中、右。我想要重置所有滑块到中间,如果另一个是改变的。可以把这看作是一个UI,在这个UI中,您向左或向右滑动以显示可以对列表中的项目执行的操作。我不希望多个项目同时显示它们的操作-因此,在其中一个项目上滑动应该会将所有其他项目重新设置为初始状态。
文档中说,在滑块事件中,"this“总是指有问题的滑块,但由于某种原因,它指的是窗口,我不知道为什么。
下面是一个简单的动作https://codepen.io/gurubob/pen/MWawvQK示例
$(() => {
var swipers = [];
function initSwiper(element) {
var swiper = new Swiper(element, {
// Optional parameters
direction: 'horizontal',
loop: false,
initialSlide: 1,
on: {
slideChange: () => {
// The docs say that "this" is always the instance of
// the swiper in any events, but here "this" is the
// window and I can't spot why????
// Change all other swipers back to initial slide:
var thisSwiper = this;
swipers.forEach(swiper => {
if(swiper != thisSwiper) swiper.slideTo(1);
})
}
}
})
swipers.push(swiper);
}
$(function(){
$('.swiper-container').each((idx, element) => {
initSwiper(element);
});
})
})你能发现我做错了什么吗?
发布于 2020-04-13 09:25:58
这是因为您在传递给Swiper的选项中使用箭头函数作为slideChange属性的值。
箭头函数使用父作用域,而不是使用新的作用域:Arrow functions MDN
您可以只使用swiper变量,而不使用this
slideChange: () => {
swipers.forEach(swiperItem => {
if(swiper != swiperItem) swiperItem.slideTo(1);
})
}另一种选择是单独添加事件侦听器:
var swiper = ...;
swiper.on('slideChange', () => ...)https://stackoverflow.com/questions/61180245
复制相似问题