【问题标题】:Getting a "Uncaught TypeError: Cannot read property 'addEventListener' of null"获取“未捕获的类型错误:无法读取 null 的属性‘addEventListener’”
【发布时间】:2021-05-12 06:13:21
【问题描述】:

我正在练习我的 vanilla JS 并尝试创建动态元素。我遇到了一些有趣的行为。我只是创建一个按钮,单击它,然后将其渲染到 DOM 上。但是后来我想创建另一个将鼠标悬停在 h1 元素上并更改颜色的事件,但是我得到一个“未捕获的 TypeError:无法读取属性 'addEventListener' of null”。如果 DOM 上有一个 h1,为什么它显示为 null,为什么现在说无法读取 null 的属性“addEventListener”?

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Creating Dynamic Elements</title>
</head>
<body>
  
</body>
</html>

JavaScript

// const h1 = document.querySelectorAll('h1');  
const button = document.createElement('button');
button.textContent = "Click me";
document.querySelector('body').appendChild(button);

button.addEventListener('click', function() {
  const h1 = document.createElement('h1');
  h1.textContent = 'Hello World!';
  document.querySelector('body').appendChild(h1);
});

document.querySelector('h1').addEventListener('mouseover', function() {
  alert("It works!");
});



【问题讨论】:

  • 在您尝试选择它并添加事件侦听器时没有h1
  • 它为我运行,没有任何错误

标签: javascript


【解决方案1】:

在函数内添加您的 h1 事件侦听器,因为加载时没有 h1。

const button = document.createElement('button');
button.textContent = "Click me";
document.querySelector('body').appendChild(button);

button.addEventListener('click', function() {
  const h1 = document.createElement('h1');
  h1.textContent = 'Hello World!';
  document.querySelector('body').appendChild(h1);

  h1.addEventListener('mouseover', function() {
    alert("It works!");
  });
});

【讨论】:

    【解决方案2】:

    它不会起作用,因为执行 addEventListner 行时您的 DOM 没有任何“h1”元素 您可以改为将其移动到按钮事件侦听器函数中

    同样document.querySelect() 只选择带有选择器的第一个元素 如果您希望它与您添加的每个 h1 元素一起使用,您应该使用引用您在代码中动态创建的元素的变量

    const button = document.createElement('button');
    button.textContent = "Click me";
    document.querySelector('body').appendChild(button);
    
    button.addEventListener('click', function() {
      const h1 = document.createElement('h1');
      h1.textContent = 'Hello World!';
      document.querySelector('body').appendChild(h1);
      /* This will only select the first h1 element in the whole document
      document.querySelector('h1').addEventListener('mouseover', function() {
        alert("It works!");
      });
      */
      //This will add the event listener to every h1 element you create
      h1.addEventListner('mouseover', function() {
        alert("It works!");
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-11
      • 2021-03-07
      • 2020-12-31
      • 1970-01-01
      • 2022-01-20
      • 2021-12-31
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多