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

如何切换for循环生成的标签页的active激活类?

Shopify 循环生成标签页交互实现方案

第一步:修复现有Liquid代码问题

你当前的内容区域代码给所有循环生成的内容块都加了content-active类,会导致所有内容默认都显示,需要调整为仅首个内容块加激活类:

<div class="content-wrapper">
  {% for product in collection.products %}
    <div id="content-{{ forloop.index }}" class="content {% if forloop.first %}content-active{% endif %}">
  {% endfor %}
</div>

第二步:JavaScript 交互实现

无需绑定固定数量的标签,代码会自动适配循环生成的任意数量标签内容对:

document.addEventListener('DOMContentLoaded', function() {
  // 获取所有标签和内容元素
  const allTabs = document.querySelectorAll('.tab-wrapper > div');
  const allContents = document.querySelectorAll('.content-wrapper > .content');

  allTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      // 提取当前点击标签的序号
      const targetIndex = this.id.split('-')[1];
      // 清空所有激活状态
      allTabs.forEach(item => item.classList.remove('tab-active'));
      allContents.forEach(item => item.classList.remove('content-active'));
      // 给当前选中的标签和对应内容加激活类
      this.classList.add('tab-active');
      document.getElementById(`content-${targetIndex}`).classList.add('content-active');
    })
  })
})

逻辑说明

  • 完全适配循环生成的动态标签数量,后续调整产品展示数量无需修改JS代码
  • 依赖你现有定义的tab-序号、content-序号的ID规则做关联,不需要额外修改HTML结构
  • 点击时先全局清空激活状态再单独给目标元素加类,避免多个标签同时激活的冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 04:06:05