强制使用JavaScript重新加载页面(无需按钮)

huangapple go评论67阅读模式
英文:

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。因此,当hasReloadedfalse时,执行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.

huangapple
  • 本文由 发表于 2023年6月8日 03:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定