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

如何改写JS实现从页面任意位置拉取Tab内容(适配WordPress短码)

标签页内容外部加载解决方案

问题背景

现有标签页代码无法满足需求:因为WordPress短码不能在标签容器内执行,必须将内容放在页面其他位置,再通过JS拉取显示到标签区域。

原JS代码

const btn = [].slice.call(document.getElementsByTagName('button'))
btn.forEach((item, index) => {
  item.addEventListener('click', function() {
    btn.forEach((item) => {
      item.classList.remove('active')
    })
    item.classList.add('active')
    document.getElementById('tab').setAttribute('data-tab', index)
  })
})

原HTML结构

<div class="wrapper">
  <button> Tab 1</button>
  <button> Tab 2</button>
  <button> Tab 3</button>
  <div id="tab" class="tabs inliner">
    <div>
      <h2> CONTENT HAST TO BE HERE </h2>
    </div>
    <div>
      <h2> OR HERE </h2>
    </div>
  </div>
</div>

改写方案

核心是给按钮和外部内容做关联标记,点击时动态拉取对应内容到显示容器。

1. 调整HTML结构

把标签内容移到页面任意位置,给按钮加data-target属性指向对应内容的ID,显示容器留空:

<div class="wrapper">
  <button data-target="tab-content-1"> Tab 1</button>
  <button data-target="tab-content-2"> Tab 2</button>
  <button data-target="tab-content-3"> Tab 3</button>
  <!-- 这是用来显示内容的容器 -->
  <div id="tab-display" class="tabs inliner"></div>
</div>

<!-- 页面任意位置放外部内容,WordPress短码直接写这里就行 -->
<div id="tab-content-1" class="tab-hidden">
  [your-wordpress-shortcode-1]
  <h2>标签1的外部内容</h2>
</div>
<div id="tab-content-2" class="tab-hidden">
  [your-wordpress-shortcode-2]
  <h2>标签2的外部内容</h2>
</div>
<div id="tab-content-3" class="tab-hidden">
  [your-wordpress-shortcode-3]
  <h2>标签3的外部内容</h2>
</div>

2. 加个CSS隐藏外部内容

避免外部内容在页面上显示:

.tab-hidden {
  display: none;
}

3. 重写JS逻辑

实现点击按钮加载对应外部内容:

// 获取所有标签按钮和显示容器
const tabButtons = document.querySelectorAll('.wrapper button');
const tabDisplay = document.getElementById('tab-display');

// 页面加载时默认显示第一个标签内容
if (tabButtons.length > 0) {
  const firstContentId = tabButtons[0].getAttribute('data-target');
  tabDisplay.innerHTML = document.getElementById(firstContentId).innerHTML;
  tabButtons[0].classList.add('active');
}

// 给每个按钮绑定点击事件
tabButtons.forEach(button => {
  button.addEventListener('click', () => {
    // 重置所有按钮的激活状态
    tabButtons.forEach(btn => btn.classList.remove('active'));
    button.classList.add('active');
    
    // 获取要加载的内容ID,然后替换显示容器的内容
    const targetId = button.getAttribute('data-target');
    const targetContent = document.getElementById(targetId);
    if (targetContent) {
      tabDisplay.innerHTML = targetContent.innerHTML;
    }
  });
});

补充说明

  • 这种方式完全不受内容位置限制,WordPress短码可以放在页面任何地方,只要ID和按钮的data-target对应就行
  • 如果需要保留内容里的JS事件(比如短码生成的交互),可以把innerHTML替换成克隆节点:tabDisplay.innerHTML = ''; tabDisplay.appendChild(targetContent.cloneNode(true));
  • 激活状态的样式可以自己定义,保持和原代码一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:11:34