简体   繁体   English

document.queryselector 返回 null 值

[英]document.queryselector returns null value

I am currently building a tic tac toe game with HTML, CSS, and Vanilla JS, and I have a settings button with id 'mode' and class 'settings-button' to toggle between player vs player and player vs cpu (see code below).我目前正在使用 HTML、CSS 和 Vanilla JS 构建井字游戏,并且我有一个设置按钮,ID 为“模式”和 class )。

When I run document.querySelector on the button's class, it returns a null value, which in turn causes the eventlistener line to raise an error (Uncaught TypeError: Cannot read property 'addEventListener' of null).当我在按钮的 class 上运行 document.querySelector 时,它返回一个 null 值,这反过来会导致 eventlistener 行引发错误(Uncaught TypeError: Cannot read property 'addEventListener' of null)。

I have tried using document.getElementById and putting all of my code into a window.onload block with both document methods, but I experienced the same issue in all scenarios.我尝试使用 document.getElementById 并将我的所有代码放入 window.onload 块中,并使用两种文档方法,但在所有情况下我都遇到了同样的问题。 At first I thought it could be a wifi connection issue, since I am working on repl.it for this project, but I checked other projects that have similar code and they all seemed to be working fine.起初我认为这可能是 wifi 连接问题,因为我正在为这个项目开发 repl.it,但我检查了其他具有类似代码的项目,它们似乎都工作正常。

I have also tried using document.querySelectorAll, and it returns an empty node list.我也尝试过使用 document.querySelectorAll,它返回一个空节点列表。

What should I do to fix this?我应该怎么做才能解决这个问题?

 const modeButton = document.querySelector('settings-button'); let cpu = false; function switchMode() { cpu =;cpu. this?textContent = cpu: modeText[1]; modeText[0]. } modeButton,addEventListener('click';switchMode);
 <button id="mode" class="settings-button">Player vs Player</button>

you are using settings-button as a class instead of .settings-button .您正在使用settings-button作为 class 而不是.settings-button add (.) before the class name in querySelector method在 querySelector 方法中的 class 名称之前添加 (.)

const modeButton = document.querySelector('.settings-button');

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

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