英文:
Force Reload a Page with Javascript (No Button)
问题
我正在处理一个网站,当某人访问特定页面时,我需要页面刷新。
我尝试使用location.reload()以及timeout函数,但页面一直在重新加载。我只需要对该函数进行限制,使其仅重新加载一次。
英文:
I'm working on a site, and when an individual visits a certain page, I need the page to refresh.
I tried using location.reload() as well as the timeout function, but the page kept reloading. I just need to impose a limitation on the function to have one relaod.
答案1
得分: 2
如果您需要在加载页面时执行任务,但也要根据先前的加载来确定是否应执行该任务,那么您所讨论的是将信息保留在页面外部。
localStorage
是一种常见的方法。例如,考虑以下代码:
const hasReloaded = localStorage.getItem('hasReloaded') || false;
if (!hasReloaded) {
localStorage.setItem('hasReloaded', 'true');
location.reload();
}
代码首先查找localStorage
中的值。如果该值不存在,则默认为false
。因此,当hasReloaded
为false
时,执行if
块。在该块内,将一个值写入localStorage
并重新加载页面。
下次页面加载时,再次检查该值,如果找到它,if
块就不会执行。
英文:
If you need a page to perform a task on load, but also know whether or not it should perform that task based on a previous load, then what you're taking about is persisting information outside of the page.
localStorage
is a common approach. For example, consider the following:
const hasReloaded = localStorage.getItem('hasReloaded') || false;
if (!hasReloaded) {
localStorage.setItem('hasReloaded', 'true');
location.reload();
}
The first thing the code does is look for a value in localStorage
. If the value doesn't exist, it defaults to false
. So when hasReloaded
is false
, the if
block executes. Within that block, write a value to localStorage
and reload.
The next time the page loads, when it checks the value again it finds it and the if
block doesn't execute.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论