【问题标题】:JAVASCRIPT Reload a page or a div using JSJAVASCRIPT 使用 JS 重新加载页面或 div
【发布时间】:2022-12-14 11:13:21
【问题描述】:

我有一个基于 HTML/CSS/JS 的内部网站(没有互联网),其中为雇主显示了一堆信息。数据每周变化一次。内网是基于这个搭建和阐述的:https://www.w3schools.com/howto/howto_js_vertical_tabs.asp 问题在于,当用户访问该页面时,他们看不到更新的信息,因为浏览器是从缓存中加载的。当然,在 ctrl-f5 之后一切都很好。但是,我想以更系统的方式解决这个问题。

我在这里和外面读过很多帖子,但它们对我不起作用。例如,我在 JS 中有这段代码:

const ctrlF5 = function(){
            // Match this timestamp with the release of your code
            const dateNow = Date.now();
            const lastDateTime = localStorage.getItem('lastDatetime');
            let reload = false;
            if(dateNow > lastDateTime || lastDateTime === null){
                reload = true;
            }
            localStorage.setItem('lastDatetime', Date.now());
            if(reload){
                location.reload();
            }
        };

它由 div 元素上的 onclick 事件触发,如下所示:

<button class="tablinks DCPorts" onclick="openTab(event, 'DCPorts');ctrlF5();">Ports Availability</button>

问题是,当用户单击该按钮时,页面开始快速闪烁,直到按下浏览器上的停止按钮。该页面也永远不会更新。按钮上的 onclick 事件侦听器背后的原因是因为我只想刷新相关的 div,但我还没有做到这一点,正在进行中。如果在页面加载时运行该函数,结果是相同的。 如果不是 location.reload();我使用 window.location.href = window.location.href 结果是一样的。 如何使用 JS 重新加载页面(不仅仅是刷新)?可能没有 Jquery。

【问题讨论】:

  • lastDateTime 可能是一个字符串。如果是unix时间戳,用new Date(lastDateTime)转换?

标签: javascript


【解决方案1】:

听起来您遇到的问题是单击按钮时重复调用 ctrlF5 函数,导致页面闪烁。解决此问题的一种方法是使用标志变量来跟踪页面是否已重新加载。您可以通过在页面重新加载后将 reloaded 变量设置为 true 并在再次调用 location.reload() 之前检查此变量来执行此操作。

以下是更新后的 ctrlF5 函数的外观:

 let reloaded = false;

const ctrlF5 = function(){
  // Match this timestamp with the release of your code
  const dateNow = Date.now();
  const lastDateTime = localStorage.getItem('lastDatetime');
  if (dateNow > lastDateTime || lastDateTime === null) {
    if (!reloaded) {
      // Set the flag to true to prevent the page from being reloaded again
      reloaded = true;
      location.reload();
    }
  }
  localStorage.setItem('lastDatetime', Date.now());
};

这应该可以防止多次单击按钮时页面闪烁。

对于只更新相关的div,可以使用JavaScript 找到对应id 的div,然后使用innerHTML 属性更新其内容。例如,如果要更新的 div 的 id 为 DCPorts,则可以使用以下代码更新其内容:

const div = document.getElementById('DCPorts');
div.innerHTML = 'New content for the div';

我希望这有帮助!

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2013-04-21
    • 2017-04-25
    • 2023-03-23
    • 2012-03-18
    • 2012-06-21
    相关资源
    最近更新 更多