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

Swiper.js v4.0.6自定义分页名称显示顺序错误求助

解决Swiper v4自定义分页名称显示顺序错误的问题

嘿,我帮你揪出问题根源啦!你的分页名称显示错乱主要是两个小细节没处理好,咱们一步步来修复:

问题1:数组索引与循环变量不匹配

JavaScript数组是0索引的(第一个元素索引为0,第二个为1,以此类推),但你在renderCustom的循环里从i=1开始遍历,同时直接用names[i]取值:

  • 当i=1时,取到的是names[1](也就是Item 2)
  • 当i=3时,names[3]不存在,自然显示undefined

而且Swiper的current参数是从1开始计数的,这也需要和数组索引做好对应。

问题2:jQuery选择器语法错误

你写的$("swiper-wrapper .swiper-slide")漏掉了类选择器的.,这会导致无法正确选中slide元素,取不到data-name的值(不过从你的现象来看可能是代码笔误,但还是得修正)。

修正后的完整代码

HTML(这部分没问题,保持原样即可)

<div class="swiper-container"> 
  <div class="swiper-wrapper"> 
    <div class="swiper-slide" data-name="Item 1"> 
      <p>Testing 1</p> 
    </div> 
    <div class="swiper-slide" data-name="Item 2"> 
      <p>Testing 2</p> 
    </div> 
    <div class="swiper-slide" data-name="Item 3"> 
      <p>Testing 3</p> 
    </div> 
  </div> 
  <div class="swiper-button-prev"></div> 
  <div class="swiper-button-next"></div> 
</div> 
<div class="swiper-pagination"></div>

JavaScript

var names = [];
// 修正选择器,加上类选择器的.
$(".swiper-wrapper .swiper-slide").each(function(i) {
  names.push($(this).data("name"));
});

var swiper = new Swiper('.swiper-container', {
  pagination: {
    el: '.swiper-pagination',
    type: 'custom',
    renderCustom: function(swiper, current, total) {
      // 修正拼写错误:transperent → transparent
      var text = "<span style='background-color:transparent;text-align: center;width:100%; display:block'>";
      // 循环从0开始,匹配数组的0索引
      for (let i = 0; i < total; i++) {
        // current从1开始,所以用i+1和current比较
        if (current == i + 1) {
          text += "<span style='display:inline-block;border-top:3px solid red;text-align:left;margin-right:4px;width: 20%;color:red;padding:5px;'>" + names[i] + "</span>";
        } else {
          text += "<span style='display:inline-block;border-top:3px solid white;text-align:left; margin-right:4px;width: 20%;color:white;padding:5px;'>" + names[i] + "</span>";
        }
      }
      text += "</span>";
      return text;
    }
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  }
});

额外修正小细节

顺便帮你改了transperent的拼写错误(正确是transparent),避免样式不生效~

现在测试一下,分页栏就会正确显示Item 1、Item 2、Item 3,选中状态也能完美对应当前幻灯片啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:55:50