事件侦听器无法正常运行,因为 javascript returns [object HTMLElement]

EventListeners don't function proparly because javascript returns [object HTMLElement]

我正在尝试将 class 添加到有关鼠标悬停的部分,并在鼠标移出时将其删除。但是,eventlistnere 仅在一个部分起作用,对于其余部分,它 returns <[object HTMLElement]>.

非常感谢您的帮助

let sections = document.querySelectorAll("section");
let list = document.getElementById("navbar__list");

// this function changes the background of the section to show it is the active one
const activeSection = section => {
 console.log(`here ${section}`);
 section.className = "your-active-class";
};

// this function return the section to its normal status when the user is not viewing it anymore
const inactiveSection = section => {
 console.log(`there ${section.id}`);
 section.className = "";
};
for (section of sections) {
 section.addEventListener("mouseover", () => {
   activeSection(section);
 });
 section.addEventListener("mouseout", () => {
   inactiveSection(section);
 });
 let point = document.createElement("li");
 let link = document.createElement("a");
 link.className = "menu__link";
 link.textContent = section.id;
 link.href = `#${section.id}`;
 point.appendChild(link);
 list.appendChild(point);
}
  1. 在控制台看到[object HTMLElement]是绝对正常的。当你打电话
console.log(`here ${section}`)

section 无法转换为 sting,因此将其替换为 [object HTMLElement]

  1. 现在,您的脚本由于其他原因无法正常工作。当你写
for (section of sections) {

您创建了一个全局变量 section,它在每次迭代时都会被覆盖。最后一次迭代是您的最后一个 <section> 元素。当调用侦听器回调函数时,它始终是作为参数传递的 <section>

要解决这个问题,您需要将 section 变量限定在 for 循环块中,就像这样

for (let section of sections) {