繁体   English   中英

为什么我不断收到此错误? 未捕获的类型错误:无法读取 null 的属性“classList”

[英]Why do I keep getting this error? Uncaught TypeError: Cannot read property 'classList' of null

当我单击最后一个标题为“联系我”的选项卡时,它不会显示任何内容。

<body>
  <ul class="tabs">
    <li data-tab-target="#home" class="active tab">Home</li>
    <li data-tab-target="#pricing" class="tab">Pricing</li>
    <li data-tab-target="#about" class="tab">About</li>
    <li data-tab-target="#Contact Me" class="tab">Contact Me</li>
  </ul>
  
  <div class="tab-content">
    <div id="home" data-tab-content class="active">
      <h1>Home</h1>
      <p>This is the home</p>
    </div>
    <div id="pricing" data-tab-content>
      <h1>Pricing</h1>
      <p>Some information on pricing</p>
    </div>
    <div id="about" data-tab-content>
      <h1>About</h1>
      <p>Let me tell you about me</p>
    </div>
    <div id="Contact Me" data-tab-content>
      <h1>Contact</h1>
      <p>hello let me tell</p>
    </div>
  </div>

</body>
</html>

JS:这就是错误(Uncaught TypeError: Cannot read property 'classList' of null)所在,我不确定我做错了什么。

const tabs = document.querySelectorAll('[data-tab-target]')
const tabContents = document.querySelectorAll('[data-tab-content]')

tabs.forEach(tab => {
  tab.addEventListener('click', () => {
    const target = document.querySelector(tab.dataset.tabTarget)
    tabContents.forEach(tabContent => {
      tabContent.classList.remove('active')
    })
    tabs.forEach(tab => {
      tab.classList.remove('active')
    })
    tab.classList.add('active')
    target.classList.add('active')
  
  })
})

只需删除id="Contact Me"中的空格

<div id="ContactMe" data-tab-content>
  <h1>Contact</h1>
  <p>hello let me tell</p>
</div>

这可能是因为您试图在加载元素之前访问它。

尝试将您的代码包装在window.onload

像这样:

window.onload = function () {
  // paste your whole JS Code here
}

暂无
暂无

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

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