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

Shopify中如何用JavaScript实现仅显示选中div、隐藏其余未选div

解决方案

1. 修改JS函数

你原有的代码仅处理了当前点击对应div的状态,没有隐藏其余div。只需在函数中先把所有div统一设置为隐藏,再处理当前选中div的显示即可,修改后完整代码如下:

function showDiv(index) {
  let one = document.getElementById('shopify-section-track_order_details');
  let two = document.getElementById('shopify-section-returns_exchanges_details');
  let three = document.getElementById('shopify-section-contact_us_details');
  let four = document.getElementById('shopify-section-order_status_details');
  let five = document.getElementById('shopify-section-shipping_returns_details');
  let six = document.getElementById('shopify-section-corporate_details');
  let seven = document.getElementById('shopify-section-product_help_details');
  let eight = document.getElementById('shopify-section-ambassador_details');
  let nine = document.getElementById('shopify-section-FAQ_details');

  let arrHelp = [one, two, three, four, five, six, seven, eight, nine];
  // 先把所有关联div设为隐藏
  arrHelp.forEach(item => {
    if(item) item.style.display = 'none';
  });
  let el = arrHelp[index - 1];
  if(el) {
    // 如果需要支持再次点击当前按钮隐藏对应div,保留下面的三目判断逻辑
    el.style.display = el.style.display === 'block' ? 'none' : 'block';
    // 如果不需要点击当前按钮隐藏,固定点击就展示对应div,直接写 el.style.display = 'block' 即可
  }
}

2. Liquid代码优化建议

你当前循环输出的a标签使用了固定id pageLink,同一页面内id不允许重复,建议去掉id属性或者改为class属性,修改后参考代码:

{% for block in section.blocks %}  
  <a class="pageLink" onclick="showDiv({{ forloop.index }})" >
    {{ block.settings.button }}
    <i id="navArrow{{ forloop.index }}" class="fad fa-chevron-right navArrow" style="float: right"></i>
  </a>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:36:06