简体   繁体   English

Javascript:使用“开-关”按钮反复自动刷新网页

[英]Javascript: Repeatedly Auto Refresh Webpage with an ON-OFF Buttons

I would like to use Javascript to auto-refresh my webpage while users can choose to turn on/turn off the auto-refresh function with two different buttons (Please be aware that the buttons are using <label> and <input> tag). 我想使用Javascript自动刷新网页,而用户可以选择使用两个不同的按钮打开/关闭自动刷新功能(请注意,这些按钮使用<label><input>标签)。 I have tried my best to write the code but I still do not know how to link up these two codes so that it can function correctly. 我已经尽力编写了代码,但是我仍然不知道如何链接这两个代码,以便它们可以正常运行。

Also, if user choose the buttons of auto-refresh ON, I want to keep auto refresh continuously after its first load instead of just auto refreshing only once. 另外,如果用户选择“自动刷新”按钮,则我希望在第一次加载后连续保持自动刷新,而不是仅自动刷新一次。

Would you please help me to correct my codes, please? 请您帮我改正我的密码吗? Thank you. 谢谢。

The code for ON and OFF buttons (two individual buttons): ON和OFF按钮(两个单独的按钮)的代码:

<div class="page-header-actions" data-toggle="buttons" role="group">
  <label class="btn btn-outline btn-primary active">
    <input type="radio" name="options" autocomplete="off" value="autorefreshoff" checked />
    <i class="icon wb-check text-active" aria-hidden="true"></i> Auto Refresh OFF
  </label>
  <label onClick="startrefreshon" class="btn btn-outline btn-primary">
    <input type="radio" autocomplete="off" value="autorefreshon" />
    <i class="icon wb-check text-active" aria-hidden="true"></i> Auto Refresh ON
  </label>
</div>

The code for auto-refresh function: 自动刷新功能的代码:

<script type='text/javascript'>
setTimeout(function(){
   window.location.reload(1);
}, 5000);
</script>

Here are a few things you need to do: 这是您需要做的几件事:

  1. Both the input type="radio" should have same name . 两个input type="radio"应该具有相同的name
  2. Give the 'auto refresh on' button an ID, so that you can reference it easily in JavaScript code (say auto-refresh-checkbox ). 给“自动刷新”按钮指定一个ID,以便您可以轻松地在JavaScript代码中引用它(例如auto-refresh-checkbox )。
  3. Write a reload function that checks if the checkbox is checked 编写一个重载函数,检查该复选框是否被checked

code: 码:

function reloadPage(){
  var refreshEnabled = document.getElementById('auto-refresh-checkbox');
  if(refreshEnabled.checked) {
    window.location.reload(1);
  }
}
  1. Then call this function via setInterval 然后通过setInterval调用此函数

setInterval(reloadPage, 5000);


PS: The checked "auto refresh" radio will lose it's value on page reload, so you might have to save the value using localStorage or something else. PS:选中的“自动刷新”无线电将在重新加载页面时丢失其值,因此您可能必须使用localStorage或其他方式保存该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM