在JavaScript之后刷新页面并运行功能

Los*_*oul 7 javascript reload

您好我正在尝试刷新页面,然后在刷新完成后运行一个函数.然而,我现在的代码运行funxtion然后它只刷新意味着我失去了函数的功能.有办法解决吗?

我的代码是:

function reloadP(){
    document.location.reload();
    myFunction();
}

<button onclick: "reloadP()">Click</button>    
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 18

您需要在myFunction()加载页面时调用.

window.onload = myFunction;
Run Code Online (Sandbox Code Playgroud)

如果您只想在重新加载页面时运行它,而不是在第一次加载页面时运行它,您可以使用它sessionStorage来传递此信息.

window.onload = function() {
    var reloading = sessionStorage.getItem("reloading");
    if (reloading) {
        sessionStorage.removeItem("reloading");
        myFunction();
    }
}

function reloadP() {
    sessionStorage.setItem("reloading", "true");
    document.location.reload();
}
Run Code Online (Sandbox Code Playgroud)

DEMO


小智 5

function myFunction() {
    document.getElementById("welcome").textContent = "Welcome back!";
}

window.onload = function() {
    var reloading = sessionStorage.getItem("reloading");
    if (reloading) {
        sessionStorage.removeItem("reloading");
        myFunction();
    }
}

function reloadP() {
    sessionStorage.setItem("reloading", "true");
    document.location.reload();
}

Run Code Online (Sandbox Code Playgroud)

演示: https: //jsfiddle.net/barmar/5sL3hd74/