You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么在甘特图中展示用户状态时网页返回undefined?

问题根因与修复方案

核心错误点

  • 你用来输出结果的代码存在两处逻辑错误:
    1. Array.push()的返回值是执行push操作后数组的新长度,不是你插入的DOM元素,因此你获取到的stat本身就不是用户状态值
    2. 页面加载完成后调用document.write()会清空整个原有DOM内容再写入新内容,这是你页面出现异常服务器数据的直接原因
  • 状态切换函数里的在线状态文本拼写错误,你写的是Activ,缺失末尾的e,导致无法正常显示Active
  • CSS中.status类的宽度设置为2.5%,宽度过窄会导致文本被截断,无法完整展示状态内容

修正后的完整代码

HTML

<div class="app">
  <h5 class="status">User Status</h5>
</div>

CSS

.app {
  height: 4.7vh;
  width: auto;
  display: flex;
  align-items: center;
  background-color: #000000;
  position: relative;
  margin-left: 261px;
  margin-bottom: 5%;
}

.status {
  margin-left: 10px;
  font-size: 15px;
  width: auto;
}

.status.online {
  color: #41a700;
}

.status.offline {
  color: #f15c4f;
}

JavaScript

function userStatus(online) {
  const element = document.querySelector('.status');
  if (online) {
    element.classList.remove('offline');
    element.classList.add('online');
    element.innerText = 'Active';
  } else {
    element.classList.remove('online');
    element.classList.add('offline');
    element.innerText = 'Pause';
  }
}
window.addEventListener('load', () => {
  userStatus(navigator.onLine);
  window.addEventListener('online', () => {
    userStatus(true);
  });
  window.addEventListener('offline', () => {
    userStatus(false);
  });
});

额外说明

删除你原本写的那两行输出代码即可,状态会直接渲染在.status元素中,不需要额外调用方法输出。

内容的提问来源于stack exchange,提问作者Muneeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:45:07