location.reload(),JavaScript,HTML [英] location.reload(), Javascript,HTML
问题描述
当我尝试在HTML文件中的按钮中使用以下代码时,我总是遇到问题.
onClick=window.location.reload();
mapGenerator();
页面重新加载,但未显示构成D3JS视图的javascript(mapGenerator).我在做什么错了?
location.reload()
将立即重新加载页面并阻止执行以下任何代码.
但是,您可以创建一个函数,该函数在页面(重新)加载后执行 :
window.onload = function() {
mapGenerator();
};
此方法将在页面完全加载后每 次运行.若要仅在使用location.reload()
重新加载页面后运行代码,可以创建一种方法来处理点击,方法是设置cookie,然后重新加载页面.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
这将需要您将onClick值更改为onClick="handleClick();"
.现在,每当页面加载时,您都可以检查cookie是否已设置.您的window.onload
函数现在更改为:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
检查是否存在cookie-Michael Berkowski的答案
在重新加载后,是否要取消设置cookie由您决定-如果不希望,则页面将在每次加载页面时运行mapGenerator
函数,直到cookie过期.
如果您需要有关Cookie的更多帮助,请查看 W3Schools的教程. /p>
I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload()
will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload()
, you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();"
. Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload
function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator
on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
这篇关于location.reload(),JavaScript,HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!