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

如何用循环简化多eq()实例的jQuery滚动跳转代码?

精简导航跳转的jQuery代码方案

问题背景

使用CMS集合无法为区块分配特定ID,现有点击导航跳转到对应区块的jQuery代码重复冗余,希望精简为单个函数,最多可能存在9个实例,询问能否通过循环处理eq(0)至eq(9)实现。

原始代码

HTML

<nav>
  <div class="link">Link 1</div>
  <div class="link">Link 2</div>
  <div class="link">Link 3</div>
</nav>

<div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

冗余的jQuery代码

$(".link")
  .eq(0)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(0).offset().top },
      1000
    );
  });

$(".link")
  .eq(1)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(1).offset().top },
      1000
    );
  });

$(".link")
  .eq(2)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(2).offset().top },
      1000
    );
  });

解决方案

当然可以实现,推荐两种精简方式:

方式一:循环绑定事件

通过循环遍历索引0到8(对应最多9个实例),为每个.link绑定点击事件,匹配相同索引的.item:

for (let i = 0; i < 9; i++) {
  $(".link").eq(i).on("click", function() {
    $("html, body").animate({
      scrollTop: $(".item").eq(i).offset().top
    }, 1000);
  });
}

注意:这里用let声明循环变量,避免闭包导致的索引值异常问题。

方式二:利用元素索引(更简洁灵活)

直接为所有.link绑定统一的点击事件,通过$(this).index()获取当前点击元素的索引,自动匹配对应位置的.item,无需硬编码数量,适配任意数量的实例:

$(".link").on("click", function() {
  const currentIndex = $(this).index();
  $("html, body").animate({
    scrollTop: $(".item").eq(currentIndex).offset().top
  }, 1000);
});

这种方式更推荐,代码更简洁,且能自动适配实际存在的导航和区块数量,无需修改代码即可应对实例数量变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:40:54