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

点击div将ID加入URL后,点击关闭按钮无法移除URL中的ID

解决点击关闭按钮无法移除URL Hash的问题

我已经实现了点击class为speakers--card的div时,将其ID添加到URL末尾作为Hash的功能,但点击该div内class为speakers--overlay-close的关闭按钮时,无法移除URL中的#及对应ID。尝试过split等函数,但URL仍保持带有#和ID的状态,现有代码如下:

var myDivs = document.getElementsByClassName('speakers--card');
var closeDiv = document.getElementsByClassName('speakers--overlay-close');

for(var i = 0; i < myDivs.length; i++) {
    myDivs[i].addEventListener('click', function (event) {
      console.log(this.getAttribute("id"));
      let thisID = this.getAttribute("id");
      window.location.href = window.location.href + "#" + thisID;
    });
}

问题根源

  1. 事件冒泡:关闭按钮是speakers--card的子元素,点击它时事件会往上冒泡到父元素的点击事件,导致刚移除Hash,又被父元素的事件重新加回去。
  2. Hash叠加:直接拼接window.location.href会导致多次点击卡片后,URL里的Hash变成#id1#id2这种重复格式,后续用split处理自然无效。

修复方案

给关闭按钮单独加事件,阻止冒泡,同时优化卡片的Hash设置逻辑:

var myDivs = document.getElementsByClassName('speakers--card');
var closeDivs = document.getElementsByClassName('speakers--overlay-close');

// 处理卡片点击
for(var i = 0; i < myDivs.length; i++) {
    myDivs[i].addEventListener('click', function (event) {
        // 过滤掉点击关闭按钮的情况(双重保险)
        if(event.target.classList.contains('speakers--overlay-close')) return;
        
        const cardId = this.getAttribute("id");
        // 直接设置hash,避免重复拼接
        window.location.hash = cardId;
    });
}

// 处理关闭按钮点击
for(var i = 0; i < closeDivs.length; i++) {
    closeDivs[i].addEventListener('click', function (event) {
        // 阻止事件冒泡,不让父卡片的点击事件触发
        event.stopPropagation();
        // 清空URL的Hash
        window.location.hash = '';
        
        // 可选:如果不想让清空Hash的操作留下历史记录,用下面这行代替上面的hash设置
        // history.replaceState(null, document.title, window.location.pathname + window.location.search);
    });
}

关键说明

  • event.stopPropagation():彻底阻断事件向上传递,确保点击关闭按钮时,父卡片的点击逻辑不会被触发。
  • window.location.hash = '':直接操作URL的Hash部分,比拼接href更可靠,不会出现叠加问题。
  • history.replaceState:如果希望用户点击浏览器后退时,跳过清空Hash的步骤,就用这个方法替换hash设置,它会替换当前历史记录而不是新增一条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:03:29