簡體   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