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

如何选中多个DOM元素并实现点击切换可见性功能

问题根源

  • HTML 规范要求id属性全局唯一,你为多个span设置了相同的hidden-th id,导致document.getElementById()只能匹配到第一个符合条件的元素,无法覆盖所有需要控制的隐藏内容。
  • 使用getElementsByClassName返回的是类数组的元素集合,不能直接对集合整体设置样式属性,需要遍历集合逐一操作每个元素。

修复方案

1. 优化HTML结构

移除所有span上重复的id="hidden-th"属性,仅保留class="hidden-th",同时将点击事件绑定到行元素上,减少冗余绑定:

<tr onclick="toggleRowHiddenContent(this)">
  <th class="course-title">Autogén tréning sajátélmény <br><span class="hidden-th">100 órás képzés részeként</span></th>
  <th class="course-category">30 óra</th>
  <th class="course-title">Budapest <br><span class="hidden-th">Szentkirályi u. 10.</span></th>
  <th class="course-category">Lipárdy Krisztina <br><span class="hidden-th"><a href="mailto:xy.xy@xy.com" target="_blank">xy.xy@xy.com</a></span></th>
  <th class="course-title">Kedzés: 2021. szeptember <br><span class="hidden-th">hétfőn 16 óra után hetente</span></th>
  <th class="course-category">2300 Ft /tanóra</th>
  <th class="course-title">BETELT A CSOPORT <br><span class="hidden-th">Előfeltétel: pszichológus végzettség és első interjú</span></th>
</tr>

2. 补充默认隐藏样式

在CSS中添加规则,让隐藏内容默认不显示:

.hidden-th {
  display: none;
}

3. 替换JS逻辑

重写显隐控制函数,遍历当前点击行下的所有隐藏span逐一切换状态:

function toggleRowHiddenContent(row) {
  // 仅获取当前点击行内的隐藏span,避免影响其他行
  const hiddenSpans = row.querySelectorAll('.hidden-th');
  hiddenSpans.forEach(span => {
    span.style.display = span.style.display === 'block' ? 'none' : 'block';
  })
}

修改后点击整行即可同步切换当前行所有隐藏内容的显隐状态,如果后续新增多行表格,各行的显隐控制相互独立不会互相干扰。

内容的提问来源于stack exchange,提问作者Bálint Forgács

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:39:02