简体   繁体   English

location.reload(),Javascript,HTML

[英]location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file. 当我尝试在HTML文件的按钮中使用以下代码时,我总是遇到问题。

onClick=window.location.reload();
mapGenerator();

The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. 页面重新加载但是没有出现创建D3JS视图的javascript(mapGenerator)。 What am I doing wrong? 我究竟做错了什么?

location.reload() will immediately reload the page and prevent any following code to execute. location.reload()将立即重新加载页面并阻止执行任何后续代码。

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. 要仅在使用location.reload()重新加载页面后运行代码,您可以创建一个方法,通过设置cookie然后重新加载页面来处理单击。

function handleClick() {
    document.cookie="reload=true";
    location.reload();
}

This would require you to change your onClick value to onClick="handleClick();" 这将要求您将onClick值更改为onClick="handleClick();" . Now, whenever the page loads, you can check whether the cookie has been set. 现在,无论何时加载页面,您都可以检查cookie是否已设置。 Your window.onload function now changes to this: 您的window.onload函数现在更改为:

window.onload = function() {
    if(document.cookie.indexOf("reload") >= 0) {
        mapGenerator();
    }
}

Checking if a cookie exists - answer by Michael Berkowski 检查cookie是否存在 - 由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. 在重新加载之后,由您决定是否要取消设置cookie - 如果不这样,页面将在每个页面加载时运行mapGenerator函数,直到cookie过期。

If you need more help with cookies, check out W3Schools' tutorial . 如果您需要更多关于cookie的帮助,请查看W3Schools的教程

As per your description mentioned above two actions are to be taken on click. 根据您上面提到的描述,点击即可采取两项措施。 As the first action reloads the page the second action is lost. 当第一个操作重新加载页面时,第二个操作将丢失。 If you want any action to be taken on load of the page, mention the same on onload event of the page. 如果您希望在加载页面时执行任何操作,请在页面的onload事件中提及相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM