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

如何在HTML与JavaScript中通过ID实现点击后展示对应视频

问题修复方案

原有代码的核心问题

  • ID重复违反HTML规范:页面内所有ID必须唯一,你多处复用id="video"、id="title",且按钮ID和父容器ID完全重复,导致DOM选择逻辑完全失效
  • JS逻辑错误:getId返回的点击ID没有被后续函数接收使用,showVideo内的for循环语法错误,没有实现按点击位置匹配对应元素的逻辑

可扩展修复方案

以下方案支持无限新增视频组,仅需保证每个视频组的父容器ID唯一即可,无需修改JS逻辑:

<!DOCTYPE html>
<html>
<head>
<style>
/* 用类选择器替代ID选择器,适配多组元素 */
.video {
  display: none;
}
</style>
</head>
<body>
<!-- 第一组视频 -->
<div id="group-000">
  <div class="video">     
    <iframe style="position:relative;top:0;width:100%" src="https://www.youtube.com/embed/KfDB9e_cO4k" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  </div>
  <div class="title">
    <h3>Video 1</h3>
  </div>
  <!-- 点击直接把当前按钮所属的父组ID传入处理函数 -->
  <button type="button" onclick="showVideo('group-000')">Show</button>
</div>

<!-- 第二组视频 -->
<div id="group-111">
  <div class="video">     
    <iframe style="position:relative;top:0;width:100%" src="https://www.youtube.com/embed/6dGYVKt1zw4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  </div>
  <div class="title">
    <h3>Video 2</h3>
  </div>
  <button type="button" onclick="showVideo('group-111')">Show</button>
</div>

<script>
function showVideo(groupId) {
  // 定位到当前点击的视频组容器
  const group = document.getElementById(groupId)
  // 只修改当前组内的视频和标题显示状态
  group.querySelector('.video').style.display = "block"
  group.querySelector('.title').style.display = "none"
}
</script>
</body>
</html>

新增视频组操作方法

新增组时仅需复制上述一组视频的结构,修改父容器ID为新的唯一值,同时把按钮onclick里传入的ID和父容器ID保持一致即可,无需修改其他代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:54:02