gpt4 book ai didi

如果按下按钮,Javascript 自动刷新 HTML

转载 作者:行者123 更新时间:2023-12-01 02:05:46 25 4
gpt4 key购买 nike

我有以下项目:

<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');
}
}

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

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

最佳答案

DOM element.classList property 是您一直在使用的关键,但您还需要使用 timer 异步计数并刷新页面。

现在,当页面刷新时,有关前一个页面的所有数据都将丢失,因此您必须存储所需的数据,然后将其拉回。这可以通过多种方式完成,但是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>

关于如果按下按钮,Javascript 自动刷新 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50121300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com