You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swiper JS 第2页及后续页面Back按钮点击无响应问题求助

问题原因

document.querySelector() 只会返回整个页面中第一个匹配指定选择器的元素。你现在页面里一共有3个带back类的按钮,分别在第1、2、3页的slide中,你写的绑定逻辑只给第一个(也就是第1页的返回按钮)绑了点击事件,剩下两个没绑定,所以点击没反应。
你用到的page1/page2/page3类的按钮都只在首页有一个,所以querySelector能正常匹配到,绑定逻辑不受影响。

解决方法

用querySelectorAll匹配所有.back按钮,遍历每个元素绑定点击事件即可,修改后的JS代码如下:

const swiper = new Swiper('.swiper', {
  direction: 'horizontal',
  parallax: true,
});

// 给所有back按钮绑定点击事件
document.querySelectorAll('.back').forEach(btn => {
  btn.onclick = () => {
    swiper.slideTo(0)
  }
})

document.querySelector('.page1').onclick = () => {
  swiper.slideTo(1)
}

document.querySelector('.page2').onclick = () => {
  swiper.slideTo(2)
}

document.querySelector('.page3').onclick = () => {
  swiper.slideTo(3)
}

后续如果需要给多实例的同类元素绑定事件,统一用querySelectorAll遍历绑定即可。

内容的提问来源于stack exchange,提问作者Anastay Kaiser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:06:10