簡體   English   中英

document.querySelector() 不起作用

[英]document.querySelector() does not working

有沒有依賴問題? 因為我使用的是唯一的純 javascript,沒有 jquery 或任何東西。 使用 node.js
這是我的代碼

 window.onload()=function(){ var left=document.querySelector('.left'); var right=document.querySelector(".right"); var container=document.querySelector(".container"); console.log(left); left.addEventListener('mouseenter',()=>{ container.classList.add('hover-left'); }) left.addEventListener('mouseleave', () => { container.classList.remove('hover-left'); }) right.addEventListener('mouseenter', () => { container.classList.add('hover-right'); }) right.addEventListener('mouseleave', () => { container.classList.remove('hover-right'); }) }
 <div class="container"> <div class="split left"> <h1>The Designer</h1> <a href="" class="button">Read more</a> </div> <div class="split right"> <h1>The Programmer</h1> <a href="" class="button">Read more</a> </div> </div>

我在 Chrome 上收到此錯誤:

Uncaught TypeError: window.onload is not a function

去掉括號,錯誤就消失了。

但我不明白你的頁面應該如何工作。

在此處查找更多信息:

https://stackoverflow.com/questions/29927638/window-onload-work-but-chrome-console-says-uncaught-typeerror-window-onload-is

如果您使用 CSS-Selector '.' 選擇 DOM 元素對於類,您會得到一個元素列表,而不是您可以直接操作的單個元素。

如果 left、right 和 container 在頁面上只出現一次,最好使用 ids:

JS:

window.onload=function(){
    var left=document.getElementById('left');
    var right=document.getElementById("right");

    var container=document.getElementById("container");   
    console.log(left);
    left.addEventListener('mouseenter',()=>{
        container.classList.add('hover-left');

    })
    left.addEventListener('mouseleave', () => {
        container.classList.remove('hover-left');
    })
    right.addEventListener('mouseenter', () => {
        container.classList.add('hover-right');
    })
    right.addEventListener('mouseleave', () => {
        container.classList.remove('hover-right');
    })
}

HTML:

<div id="container" class="container">
   <div class="split" id="left">
      <h1>The Designer</h1>
      <a href="" class="button">Read more</a>
   </div>
   <div class="split" id="right">
      <h1>The Programmer</h1>
      <a href="" class="button">Read more</a>
   </div>
</div>

同樣作為上面的評論指出,在設置 onload 事件時不能使用括號。

如果您的 html 中的標簽中加載了任何靜態 JS 文件,請在 html 正文的末尾加載 JS。 文檔在加載 JS 之前不會准備好,因此文檔將為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM