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

如何根据点击的div的ID显示对应的弹窗内容?

解决点击对应按钮显示弹窗的问题

你的问题核心是**document.querySelector(".popup")只会选中页面中第一个class为popup的元素**,所以不管点哪个按钮,都是第一个弹窗显示。下面给你两种简单的解决方法:

方法一:通过this传递当前点击的按钮元素

直接在点击事件里把当前按钮的引用传给函数,然后在函数里找到这个按钮下的弹窗:

修改后的HTML和JS代码:

<div class="button" id="1" onclick="openPopup(this)">fgdjgdfjgfk
  <div class="popup">you clicked the first button</div>
</div>

<div class="button" id="2" onclick="openPopup(this)">abc
  <div class="popup">you clicked the second button</div>
</div>

<script>
  function openPopup(button) {
    // 找到当前点击按钮下的popup元素
    button.querySelector(".popup").style.width = "100%";
  }
</script>

CSS保持不变即可。

方法二:使用事件委托(更推荐)

不需要给每个按钮单独加onclick,通过给父元素绑定事件,自动识别点击的按钮,适合按钮数量多的场景:

修改后的代码:

<!-- 给所有按钮加一个父容器 -->
<div class="button-container">
  <div class="button" id="1">fgdjgdfjgfk
    <div class="popup">you clicked the first button</div>
  </div>

  <div class="button" id="2">abc
    <div class="popup">you clicked the second button</div>
  </div>
</div>

<script>
  // 获取父容器
  const container = document.querySelector('.button-container');
  // 给父容器绑定点击事件
  container.addEventListener('click', function(e) {
    // 判断点击的是.button元素
    if (e.target.closest('.button')) {
      const button = e.target.closest('.button');
      // 找到对应弹窗并显示
      button.querySelector('.popup').style.width = '100%';
    }
  });
</script>

关于ID的使用说明

你的按钮ID是用来标识唯一元素的,但这次问题里其实不需要用到ID就能解决。如果后续需要通过ID定位元素,可以用document.getElementById('1')来获取对应按钮,但当前场景下用元素的层级关系(父元素找子元素)更直接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:50:18