【发布时间】: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