【问题标题】:document.queryselector returns null valuedocument.queryselector 返回空值
【发布时间】:2020-10-29 15:17:47
【问题描述】:

我目前正在使用 HTML、CSS 和 Vanilla JS 构建一个井字游戏,并且我有一个设置按钮,其 id 为“模式”,类为“设置按钮”,用于在玩家与玩家和玩家与 CPU 之间切换(见下面的代码)。

当我在按钮的类上运行 document.querySelector 时,它返回一个 null 值,这反过来会导致 eventlistener 行引发错误(Uncaught TypeError: Cannot read property 'addEventListener' of null)。

我曾尝试使用 document.getElementById 并将我的所有代码放入一个具有两种文档方法的 window.onload 块中,但我在所有场景中都遇到了同样的问题。起初我认为这可能是 wifi 连接问题,因为我正在为这个项目开发 repl.it,但我检查了其他具有类似代码的项目,它们似乎都工作正常。

我应该怎么做才能解决这个问题?

编辑:我也尝试过使用 document.querySelectorAll,它返回一个空节点列表。

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>

【问题讨论】:

  • 这不是重复的,是错字。您的查询是 settings-button,但它会查找名为 settings-button 的元素。您要查询的是.settings-button,因为您正在寻找一个具有名为“settings-button”的的元素。

标签: javascript html dom addeventlistener htmlbutton


【解决方案1】:

您将settings-button 用作类而不是.settings-button在 querySelector 方法中的类名前添加 (.)

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

【讨论】:

    猜你喜欢
    • 2014-09-25
    • 2021-08-15
    • 2017-10-12
    • 2021-02-03
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多