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

点击collection单元格时如何实现表格数据的筛选切换?

实现思路

  • 提前把每个collection选项和对应的表格数据做关联绑定
  • 用变量记录当前选中的collection项的唯一标识
  • 点击collection单元格时更新选中标识,表格自动根据选中标识加载对应数据即可

具体实现示例(原生JS版本)

  1. 定义关联好的数据源
// 配置collection项与对应表格数据的映射关系
const collectionConfig = [
  {
    key: "category1",
    label: "分类1",
    tableRows: [
      { id: 1, name: "数据1-1", value: "123" },
      { id: 2, name: "数据1-2", value: "456" }
    ]
  },
  {
    key: "category2",
    label: "分类2",
    tableRows: [
      { id: 1, name: "数据2-1", value: "789" },
      { id: 2, name: "数据2-2", value: "012" }
    ]
  }
]
// 记录当前激活的collection项标识,默认取第一个
let activeKey = "category1"
  1. 页面结构
<!-- 横向collection容器 -->
<div class="collection-wrap"></div>
<!-- 表格结构 -->
<table>
  <thead>
    <tr><th>名称</th><th>数值</th></tr>
  </thead>
  <tbody class="table-body"></tbody>
</table>
  1. 渲染与交互逻辑
const collectionWrap = document.querySelector('.collection-wrap')
const tableBody = document.querySelector('.table-body')

// 渲染横向collection
function renderCollection() {
  collectionWrap.innerHTML = ''
  collectionConfig.forEach(item => {
    const cell = document.createElement('div')
    // 给激活项加高亮类名
    cell.className = `collection-cell ${item.key === activeKey ? 'active' : ''}`
    cell.textContent = item.label
    // 绑定点击切换事件
    cell.addEventListener('click', () => {
      activeKey = item.key
      renderCollection()
      renderTable()
    })
    collectionWrap.appendChild(cell)
  })
}

// 渲染数据表格
function renderTable() {
  // 读取当前激活项对应的表格数据
  const currentTableData = collectionConfig.find(item => item.key === activeKey).tableRows
  tableBody.innerHTML = ''
  currentTableData.forEach(row => {
    const tr = document.createElement('tr')
    tr.innerHTML = `<td>${row.name}</td><td>${row.value}</td>`
    tableBody.appendChild(tr)
  })
}

// 页面初始化渲染
renderCollection()
renderTable()
  1. 基础样式补充
.collection-wrap {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}
.collection-cell {
  padding: 8px 16px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
}
.collection-cell.active {
  background: #1677ff;
  color: #fff;
  border-color: #1677ff;
}

如果使用Vue、React这类前端框架,逻辑完全一致,只需要把手动操作DOM的逻辑换成框架的响应式状态更新即可,无需手动操作DOM元素。

你要的效果参考截图:
效果示例1
效果示例2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:15:03