首页 > 解决方案 > 如果按下按钮,Javascript 会自动刷新 HTML

问题描述

我有以下物品:

<a class="btn btn-danger w-100" style='color: White' id='refresh_button' onclick="activateAutorefresh()"> ↺ </a>

我想要以下内容:如果类是btn-dangeronClick请将其更改为btn-success并激活自动刷新,超时为 5000 毫秒。如果再次单击按钮,则将类更改为btn-danger并禁用自动刷新。

所以,我有以下代码:

function activateAutorefresh(){
    if (document.getElementById("refresh_button").classList.contains('btn-danger')){
        document.getElementById("refresh_button").classList.remove('btn-danger');
        document.getElementById("refresh_button").classList.add('btn-success');
    }
    else {
        document.getElementById("refresh_button").classList.remove('btn-success');
        document.getElementById("refresh_button").classList.add('btn-danger');
    }
}

我不知道如何激活/禁用页面自动刷新。我怎样才能做到这一点?

此外,在刷新时保持当前的自动刷新状态。

标签: javascripthtmlrefresh

解决方案


DOMelement.classList属性是您一直使用的关键,但您还需要使用计时器来异步计数和刷新页面。

现在,当页面刷新时,有关前一页的所有数据都将丢失,因此您必须存储所需的数据,然后将其拉回。这可以通过多种方式完成,但localStorage最简单。

注意:由于安全原因,代码在 Stack Overflow“代码片段”环境中无法使用,但在 Web 服务器上运行时可以使用。

// Place all of the following code in a <script> that is just before the closing body tag (</body>) 

// Get reference to element
var link = document.getElementById("refresh_button");

// Retrieve the last state of the link's classes from localStorage
link.className = localStorage.getItem("linkClassList");

// Set up the event handler
link.addEventListener("click", activateAutoRefresh);

let timer = null; // Will hold reference to timer

function activateAutoRefresh(evt){

  // Test to see if the clicked element has the "btn-danger" class
  if(this.classList.contains("btn-danger")){
    this.classList.remove("btn-danger");
    this.classList.add("btn-success");
    timer = setTimeout(function(){ location = location;}, 5000); // Refresh after 5 seconds
  } else {
    this.classList.remove("btn-success");
    this.classList.add("btn-danger"); 
    clearTimeout(timer);  // Cancel the timer
  }
}

// Set the link's class list into localStorage
link.className = localStorage.setItem("linkClassList", link.className);
<a class="btn btn-danger w-100" id='refresh_button' href="#"> ↺ </a>


推荐阅读