javascript - 如果按下按钮,Javascript 会自动刷新 HTML
问题描述
我有以下物品:
<a class="btn btn-danger w-100" style='color: White' id='refresh_button' onclick="activateAutorefresh()"> ↺ </a>
我想要以下内容:如果类是btn-danger
,onClick
请将其更改为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');
}
}
我不知道如何激活/禁用页面自动刷新。我怎样才能做到这一点?
此外,在刷新时保持当前的自动刷新状态。
解决方案
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>
推荐阅读
- asp.net - asp.net中的黑屏模式弹出引导程序
- mysql - Rails 使用哈希更新多条记录
- linq - 在 LINQ 和实体框架中优化 orderby sum
- html - 引导选项卡内容未切换
- django - django 视图中的异步
- hyperledger-fabric - 错误:获取链码代码时出错链码:
:失败并出现错误:“exec:未启动” - java - 如何在构造函数的 super() 方法调用中使用子类变量 (this) 初始化其他类?
- android - 如何在原生 android 中将音频和图像作为 multipart/formdata 发布?
- angularjs - Angularjs:ng-show设置为true后不显示
- html - 如何摆脱悬停下拉菜单旁边的空白?