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

JS报Cannot read properties of null错误 电商分类标签切换功能失效

错误原因

  • HTML结构错误:提前闭合了<ul class="tabs">标签,所有li标签都被放在了ul外部,导致JS通过类选择器找不到对应激活状态的tab元素,返回null,调用classList属性时就触发了报错。
  • 选择器不匹配:JS代码中使用.sidenav .tabs .tab.is-active作为选择器,如果你的tabs外层没有加sidenav类的父容器,也会找不到对应元素。
  • 属性选择器语法错误:SwitchPage函数里查找下一个分页的选择器少了闭合的引号,[data-page="${page_id}]语法错误会导致找不到对应的分页元素。
  • 缺少空值判断:所有调用classList的位置都没有判断元素是否存在,只要找不到元素就会直接触发类型错误。

修复方案

第一步:修正HTML结构

把所有li标签放到ul内部,不要提前闭合ul,同时确保你有对应data-page属性的分页元素:

<ul class="tabs">
    <li class="tab is-active">
        <a data-switcher data-tab="1">Dell</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="2">Apple</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="3">HP</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="4">Toshiba</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="5">Lenovo</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="6">Acer</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="7">Asus</a>
    </li>
    <li class="tab">
        <a data-switcher data-tab="8">Microsoft</a>
    </li>
</ul>
<!-- 以下是对应展示的分类内容结构示例,需和tab对应 -->
<div class="pages">
    <div class="page is-active" data-page="1">Dell分类内容</div>
    <div class="page" data-page="2">Apple分类内容</div>
    <!-- 其余分类按对应规则补充即可 -->
</div>

第二步:修正JS代码

调整匹配的选择器、修复语法错误、添加空值判断避免报错:

const tab_switchers = document.querySelectorAll('[data-switcher]');

for (let i = 0; i < tab_switchers.length; i++) {
    const tab_switcher = tab_switchers[i];
    const page_id = tab_switcher.dataset.tab;

    tab_switcher.addEventListener('click', () => {
        // 如果你确实有.sidenav类的父容器,可以把选择器改回'.sidenav .tabs .tab.is-active'
        const activeTab = document.querySelector('.tabs .tab.is-active');
        if(activeTab) activeTab.classList.remove('is-active');
        tab_switcher.parentNode.classList.add('is-active');
        SwitchPage(page_id);
    });
}

function SwitchPage (page_id) {
    const current_page = document.querySelector('.pages .page.is-active');
    if(current_page) current_page.classList.remove('is-active');
    // 修复属性选择器的引号闭合错误
    const next_page = document.querySelector(`.pages .page[data-page="${page_id}"]`);
    if(next_page) next_page.classList.add('is-active');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:24:07