加载刷新页面后执行 Javascript 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8518665/
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
Executing Javascript code after loading refreshed page
提问by Loco Moco
I have a Javascript file that is split into to two parts. The first part of the code ends by refreshing the current page. I would like to try to get the second part of the code to execute as soon as the page reloads, but I am having trouble finding a way to implement this. I pretty much want a way to do
我有一个 Javascript 文件,它分为两部分。代码的第一部分以刷新当前页面结束。我想尝试在页面重新加载后立即执行代码的第二部分,但我无法找到实现此功能的方法。我非常想要一种方法
window.onload = someFunction()
except that it activates the function after reloading the page due to the first part of the Javascript. Is there an effective way to do this?
除了由于 Javascript 的第一部分,它在重新加载页面后激活该功能。有没有一种有效的方法来做到这一点?
回答by Arnaud Gourlay
You could do that using Jquery. This is executed on page loading
你可以使用 Jquery 做到这一点。这是在页面加载时执行的
$(function() {
callMyFunction()
});
回答by Gautam
Use
利用
document.onload = somefunction()
Instead . This will get executed immediately after the DOM loads .
document.onload = somefunction()
反而 。这将在 DOM 加载后立即执行。
You can also use the jQuery to do the same like
你也可以使用 jQuery 来做同样的事情
$(document).ready(function(){
somefunction();
});
回答by Shadow Wizard is Ear For You
The only way I can think of is to add query string value when refreshing, then read that value and act upon it.
我能想到的唯一方法是在刷新时添加查询字符串值,然后读取该值并对其进行操作。
You can use such code:
您可以使用这样的代码:
function ParseQueryString() {
var result = [];
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var reloaded = QS["reloaded"];
if (reloaded === "1") {
//execute second part of code
}
}
Then when reloading, redirect to same page adding ?reloaded=1
otherwise (if this flag is already raised) don't refresh the page again to avoid infinite loop.
然后在重新加载时,重定向到同一页面,?reloaded=1
否则添加(如果此标志已被提升)不要再次刷新页面以避免无限循环。