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

多个相同ID链接调用getElementById绑定点击事件仅首个生效如何解决

问题原因

HTML规范要求页面内ID必须全局唯一,document.getElementById()只会返回页面中第一个匹配对应ID的DOM元素,所以你给第二个链接设置相同ID时,JS无法获取到第二个元素,自然绑定不上点击事件。

解决方案

第一步:修改HTML代码

把两个链接的id="link"替换为class="popup-link"即可,其他结构保持不变:

<p>
  <a href="" class="popup-link"
    >Add your thoughts (this works, but the second link doesn't unless this
    one is removed).</a
  >
</p>
<a href="" class="popup-link">View or Add Comments</a><br />
<div id="popup"><iframe id="popupiframe"></iframe></div>
<div id="popupdarkbg"></div>
<p>(Click background to exit popup)</p>

第二步:修改JavaScript代码

通过document.querySelectorAll()选中所有带popup-link类的元素,循环给每个元素绑定点击事件,同时补充原代码遗漏的遮罩层显示逻辑:

// 选中所有触发弹窗的链接
const popupLinks = document.querySelectorAll('.popup-link');
// 提前缓存公共DOM元素,避免重复查询
const popup = document.getElementById('popup');
const popupIframe = document.getElementById('popupiframe');
const popupDarkBg = document.getElementById('popupdarkbg');

// 循环给每个链接绑定点击事件
popupLinks.forEach(link => {
  link.onclick = function (e) {
    e.preventDefault();
    popupIframe.src = "http://www.blankwebsite.com/";
    popup.style.display = "block";
    // 补充原代码遗漏的遮罩层显示逻辑
    popupDarkBg.style.display = "block";
  }
})

// 遮罩层点击关闭逻辑单独绑定,避免每次点击链接重复绑定
popupDarkBg.onclick = function () {
  popup.style.display = "none";
  popupDarkBg.style.display = "none";
};

CSS代码无需修改,原有样式可正常生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:12:04