//html
<div class="nav-bullets">
<div class="bullet">
<div class="tooltip" data-i=".about-us">About Us</div>
</div>
<div class="bullet">
<div class="tooltip" data-i=".skills">Our Skills</div>
</div>
<div class="bullet">
<div class="tooltip" data-i=".gallery">Our Gallery</div>
</div>
<div class="bullet">
<div class="tooltip" data-i=".timeline">TimeLine</div>
</div>
</div>
//javascript
使用一个类没有这样的问题
// Select All Bullets
const allBullets = document.querySelectorAll(".nav-bullets .bullet");
allBullets.forEach(bullet => {
bullet.addEventListener("click" , (e) => {
document.querySelector(".about-us").scrollIntoView({
behavior: 'smooth'
});
});
});
//问题
// Uncaught TypeError: Cannot read properties of null (reading 'scrollIntoView') at HTMLDivElement.<anonymous>
//但是如果我要使类动态不像这样工作
allBullets.forEach(bullet => { bullet.addEventListener("click" , (e) => { document.querySelector(e.target.dataset.i).scrollIntoView({ behavior: 'smooth' }); }); });
您将事件侦听器附加到.bullet
元素,但它没有data-i
属性,您已将其添加到子.tooltip
:
<div class="bullet"> <-- event listener is here
<div class="tooltip" data-i=".about-us"> <-- data attribute is here
About Us
</div>
</div>
这就是为什么e.target.dataset.i
是未定义的,document.querySelector(undefined)
不匹配任何元素。
将data属性移到.bullet
.