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

如何确保window.load事件监听器执行完毕后再调用this.clean()?

解决方案

首先要明确一个关键问题:你的searchUnit函数中,执行window.location.href = "units.html";后,浏览器会立即开始加载新页面,当前页面的JavaScript执行上下文会被销毁,所以这行代码后面的this.clean()以及其他操作根本不会被执行。

要实现“新页面window.load事件完成后执行clean操作”,可以按以下方式处理:

方法一:将clean逻辑迁移到新页面的load事件中

直接把clean的逻辑放到units.html的window.load事件回调末尾,确保load事件里的所有操作完成后再执行clean:

// units.html中的代码
window.addEventListener("load", () => {
    // 原来的Something other操作
    // ...

    // 执行clean操作
    clean();
}, false);

function clean() {
    // 这里写入原this.clean()的逻辑,以及你原本放在searchUnit里的后续操作
    title = document.getElementById("viewTitle");
    title.textContent = "Unità";
    sessionStorage.removeItem("product");
    sessionStorage.removeItem("supplier");
    sessionStorage.removeItem("invoice");
    sessionStorage.removeItem("status");
    // 其他clean相关操作
}

方法二:通过标记控制新页面执行clean

如果需要根据原页面的跳转指令决定是否执行clean,可以用sessionStorage传递标记:

1. 修改原页面的searchUnit函数

this.searchUnit = function (product, supplier, invoice, status) {
    // 存入标记,告诉新页面需要执行clean
    sessionStorage.setItem("needExecuteClean", "true");
    // 跳转页面
    window.location.href = "units.html";
};

2. 在units.html中处理标记

// units.html中的代码
window.addEventListener("load", () => {
    // 原来的Something other操作
    // ...

    // 检查标记,决定是否执行clean
    if (sessionStorage.getItem("needExecuteClean") === "true") {
        clean();
        // 执行后移除标记,避免下次加载重复执行
        sessionStorage.removeItem("needExecuteClean");
    }
}, false);

function clean() {
    title = document.getElementById("viewTitle");
    title.textContent = "Unità";
    sessionStorage.removeItem("product");
    sessionStorage.removeItem("supplier");
    sessionStorage.removeItem("invoice");
    sessionStorage.removeItem("status");
    // 其他clean相关操作
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:45:38