简体   繁体   English

无法使用 querySelectorAll() 向元素添加事件侦听器

[英]can't add event listeners to elements using querySelectorAll()

I'm trying to add a mouseover event on some links with the data-hide-links attribute, but it's not working at all.我试图在某些具有data-hide-links属性的链接上添加mouseover事件,但它根本不起作用。

I know that my loop is working fine and that it selects the right elements because I can console.log() the elements that I want.我知道我的循环工作正常并且它选择了正确的元素,因为我可以console.log()我想要的元素。 I also know for sure that the event listener is not adding to the element because when I look at the prototype of the elements the onmouseover property is null我也确定事件侦听器没有添加到元素中,因为当我查看元素的原型时, onmouseover属性为null

Here's the code:这是代码:

 let hideLinks = document.querySelectorAll("[data-hide-cursor]"); for (let i = 0; i < hideLinks.length; i++) { hideLinks[i].addEventListener("mouseover", () => { document.getElementById("cursor").classList.add("hide"); }); }
 #cursor { top: 0; left: 0; border-radius: 50%; pointer-events: none; z-index: 1000; } #cursor>div { border-radius: 50%; width: 1.25rem; height: 1.25rem; background: black; transition: transform 0.5s ease, opacity 0.35s ease; }
 <div id="cursor" data-cursor> <div></div> </div> <button data-hide-cursor type="submit" class="submit-mail"> Submit </button>

I tried to deconstruct the elements into an array using let [...hideLinks] =... but it did not change a thing.我尝试使用let [...hideLinks] =...将元素解构为数组,但它没有改变任何东西。

Your code works fine.您的代码工作正常。 Class hide just doesn't do anything Class hide什么都不做

 let hideLinks = document.querySelectorAll("[data-hide-cursor]"); for (let i = 0; i < hideLinks.length; i++) { hideLinks[i].addEventListener("mouseover", () => { document.getElementById("cursor").classList.add("hide"); }); }
 #cursor { top: 0; left: 0; border-radius: 50%; pointer-events: none; z-index: 1000; } #cursor>div { border-radius: 50%; width: 1.25rem; height: 1.25rem; background: black; transition: transform 0.5s ease, opacity 0.35s ease; } #cursor.hide { background: red; }
 <div id="cursor" data-cursor> <div></div> </div> <button data-hide-cursor type="submit" class="submit-mail"> Submit </button>

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

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