JavaScript 后刷新页面和运行功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41904975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh page and run function after JavaScript
提问by Lost Soul
Hello I am trying to refresh my page and then run a function once the refresh has been completed. However the code I have now runs the funxtion then it only refreshes meaning I lose what the function does. Is there a way to solve it?
您好,我正在尝试刷新我的页面,然后在刷新完成后运行一个函数。但是,我现在拥有的代码运行了函数,然后它只会刷新,这意味着我失去了该函数的作用。有办法解决吗?
My code is:
我的代码是:
function reloadP(){
document.location.reload();
myFunction();
}
<button onclick: "reloadP()">Click</button>
回答by Barmar
You need to call myFunction()when the page is loaded.
您需要myFunction()在页面加载时调用。
window.onload = myFunction;
If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorageto pass this information.
如果您只想在页面重新加载时运行它,而不是在第一次加载时运行,则可以使用sessionStorage传递此信息。
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
回答by Félix Pujols
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();
}

