如何设置'如果'和'其他'在javascript onLine Checker中

How to set the 'if' and 'else' in javascript onLine Checker?

本文关键字:其他 javascript onLine Checker 如果 设置 何设置      更新时间:2023-09-26

onLine检查器运行良好,但我想在javascript中设置"if"answers"else"。

如果状态为在线,则实用。。。您必须转到另一个链接。如果状态为脱机。。。状态必须显示此消息"正在连接…"直到设备连接。我希望在连接后,它会再次检查"如果",你通常必须转移到指定的路径。

这是HTML代码:

<p>Current network status: <span id="status">checking...</span></p>

这是javascript代码:

var statusElem = document.getElementById('status');
setInterval(function () {
  statusElem.className = navigator.onLine ? 'online' : 'offline';
  statusElem.innerHTML = navigator.onLine ? 'online' : 'offline';  
  if ('status'=='online') {
    window.location = "http://www.google.com/";
  }
  else {
    statusElem.innerHTML = navigator.onLine ? 'Online' : 'Re-connecting...';  
  }
}, 250);

感谢您抽出时间:(

因为如果你在线,你想重定向到一个新的URL,我认为你的代码可以像一样重写

var statusElem = document.getElementById('status');
setInterval(function () {
  if (navigator.onLine) {
    // you're online. Redirect to the desired URL
    // this will also clear the interval
    window.location = "http://www.google.com/";
  }
  else {
    // not online. Update the statusElem
    statusElem.className = 'offline';
    statusElem.innerHTML = 'Re-connecting';
  }
}, 250);

编辑

如果你在一个新窗口中打开链接,你可能需要清除间隔,否则它将保持每1/4秒执行一次。您可以使用clearInterval方法停止间隔

var statusElem = document.getElementById('status');
var intervalId = setInterval(function () {
  if (navigator.onLine) {
    // clear the interval
    clearInterval(intervalId);
    // you're online. Redirect to the desired URL
    window.location = "http://www.google.com/";
  }
  else {
    statusElem.className = 'offline';
    statusElem.innerHTML = 'Re-connecting';
  }
}, 250);