Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
EventListeners不';因为javascript返回[object HtmleElement]_Javascript_Addeventlistener - Fatal编程技术网

EventListeners不';因为javascript返回[object HtmleElement]

EventListeners不';因为javascript返回[object HtmleElement],javascript,addeventlistener,Javascript,Addeventlistener,我试图将类添加到mouseover的一个部分,并在mouseout时将其删除。然而,eventlistnere只在一个部分上工作,对于其余部分,它将返回 非常感谢你的帮助 let sections = document.querySelectorAll("section"); let list = document.getElementById("navbar__list"); // this function changes the backgroun

我试图将类添加到mouseover的一个部分,并在mouseout时将其删除。然而,eventlistnere只在一个部分上工作,对于其余部分,它将返回

非常感谢你的帮助

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);
}
  • 在控制台中查看
    [object HTMLElement]
    完全正常。当你打电话的时候
  • 无法转换为sting,因此它被
    [object HtmleElement]
    替换

  • 现在,你的脚本不起作用还有另一个原因。当你写作时
  • 您创建了一个全局变量
    ,它在每次迭代时都会被覆盖。最后一次迭代是最后一个
    元素。调用侦听器回调函数时,这始终是作为参数传递的相同的

    要解决这个问题,您需要将
    部分
    变量的作用域设置为for循环块,如下所示

    for (let section of sections) {
    

    您应该使用css样式来实现这一点。看一看-特别是,
    :悬停
    。谢谢,我没有看到我错过了出租。
    for (section of sections) {
    
    for (let section of sections) {