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

如何在JavaScript中根据标志条件移除hashchange事件监听器?

问题原因及解决方法

你遇到的问题核心在于:匿名函数无法被removeEventListener识别。

你给hashchange绑定的是一个匿名函数,而removeEventListener要求传入和添加时完全相同的函数引用才能生效。你代码里的this在匿名函数中指向的是window对象,根本不是当前的事件处理函数,所以移除操作完全无效。

解决步骤

  1. 将事件处理函数抽成具名函数,保留函数引用;
  2. 在合适的时机(比如弹窗关闭、isPopupOpen变为false时),用这个具名函数调用removeEventListener。

修改后的代码示例

// 定义具名的事件处理函数
function handleHashChange(e) {
  if (isPopupOpen) {
    popup.classList.remove('active');
    popup.style.transform = 'translateY(25%)';
    popup.style.height = '75%';
    isPopupOpen = false;
    
    document.head.appendChild(con);
    popcontainer.style.display = "none";
    
    // 此时弹窗已关闭,移除hashchange监听器
    window.removeEventListener("hashchange", handleHashChange);
  }
}

// 绑定事件监听器
window.addEventListener("hashchange", handleHashChange);

额外说明

如果之后需要重新启用这个hashchange监听逻辑,只需再次调用window.addEventListener("hashchange", handleHashChange)即可,因为我们复用了同一个函数引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:58:11