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

为什么通过JS设置的class类名未同步更新到HTML页面中?

问题根因

代码执行顺序错误,操作的是已被移除的旧DOM节点:

  • 你在调用app.render(view.name)之前就通过document.querySelectorAll获取了所有导航链接节点,此时拿到的是渲染前的旧DOM节点
  • app.render方法执行时会替换页面DOM内容(包含导航栏的链接元素),之前获取的旧节点已经被从页面渲染树中移除,仅存在于内存中
  • 后续给旧节点添加/移除active类的操作只会修改内存中废弃节点的属性,自然不会同步到页面当前显示的新节点上,你在控制台看到的类名更新就是这些废弃节点的属性,和当前页面的真实节点无关。
修复方案

调整代码执行顺序,先完成页面渲染,再查询当前页面的导航链接节点修改类名,修改后代码如下:

window.addEventListener("hashchange", (e) => {
  const hash = window.location.hash.replace("#", "");
  const view = routes.find((route) => {
    return route.path == hash;
  });
  // 先执行页面渲染
  app.render(view.name);
  // 渲染完成后再查询当前页面最新的导航节点
  const links = document.querySelectorAll(".nav-list--link");
  links.forEach((l) => {
    const hashHref = l.getAttribute("href").replace("/", "");
    if (hash === hashHref) {
      l.classList.add("active");
      console.log(l, l.classList);
    } else {
      l.classList.remove("active");
      console.log(l, l.classList);
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:18:02