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

如何在Svelte中为指定索引的表格单元格添加active CSS属性

Svelte实现指定单元格加active属性的最优方案

完全不需要手动操作DOM,直接用Svelte原生的声明式渲染逻辑即可实现,符合框架最佳实践:

基础实现方案

适用于索引数组长度不大的场景:

<script>
  // 单元格内容数组
  const arrCells = ['a', 'b', 'c', 'd', 'e']
  // 需激活的单元格索引数组
  const arrIdxs = [1, 3, 4]
</script>

<table>
  <tr>
    {#each arrCells as cell, index}
      <!-- 索引在激活数组中时添加active="1"属性,否则不渲染该属性 -->
      <td active={arrIdxs.includes(index) ? '1' : undefined}>{cell}</td>
    {/each}
  </tr>
</table>

上述代码渲染后的DOM结构和你给出的示例完全一致。

高性能优化方案

如果arrIdxs长度较大,可提前将其转为Set降低查找复杂度:

<script>
  const arrCells = ['a', 'b', 'c', 'd', 'e']
  const arrIdxs = [1, 3, 4]
  // 转为Set后查找复杂度为O(1),大量数据下性能更好
  const activeIndexes = new Set(arrIdxs)
</script>

<table>
  <tr>
    {#each arrCells as cell, index}
      <td active={activeIndexes.has(index) ? '1' : undefined}>{cell}</td>
    {/each}
  </tr>
</table>

扩展说明

如果后续需要动态修改激活的单元格,只需要修改arrIdxs的值,Svelte会自动更新对应单元格的active属性,全程不需要手动操作DOM。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:57:01