location.reload(), Javascript,HTML

冷暖自知 提交于 2019-12-11 11:21:22

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35538898/location-reload-javascript-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!