简体   繁体   English

使用 list.forEach() 添加事件侦听器 - 仅最后一个列表项更改

[英]adding event listeners with list.forEach() - only last list item changes

I'm new to webdesign (and coding) and this afternoon I bumped into a problem I can't solve alone.我是网页设计(和编码)的新手,今天下午我遇到了一个我无法单独解决的问题。 I hope one of you could help me.我希望你们中的一个可以帮助我。

I want to create text elements that change to green when a user hovers over it with her mouse, and to red when the mouse goes out again.我想创建文本元素,当用户将鼠标悬停在它上面时变为绿色,当鼠标再次熄灭时变为红色。 (Later, audio files will start to play when a mouse hovers over a specific object.) When you run the code, you can see that only the last element changes to red, also when a mouse hovers over the other elements. (稍后,当鼠标悬停在特定 object 上时,音频文件将开始播放。)运行代码时,您可以看到只有最后一个元素变为红色,当鼠标悬停在其他元素上时也是如此。 What is wrong with my (Javascript) code?我的(Javascript)代码有什么问题?

 const elements = [ {title: 'Element1'}, {title: 'Element2'}, {title: 'Element3'}, {title: 'Element4'}, {title: 'Element5'} ]; window.onload = () => { elements.forEach(element => { title = document.getElementById(element.title); //add event listeners title.addEventListener("mouseover", handleMouseOver = () => { mouseOver(title); }); title.addEventListener("mouseout", handleMouseOut = () => { mouseOut(title); }); }); }; //play soundfiles const mouseOver = (title) => { title.style.backgroundColor = "red"; }; const mouseOut = (title) => { title.style.backgroundColor = "#4CAF50"; };
 body { margin:0; margin-left:0em; padding:0; overflow: hidden; } canvas { margin:auto; }.compositions { display: inline-block; align-items: center; font-style: arial; font-size: 17px; list-style-type: none; text-align: center; margin-top: 5em; }.compositions p { margin-bottom: 0.8em; margin:0em 0.8em 1em 1em; display: inline-block; }.compositions input { background-color: #4CAF50; /* Green */ border: none; border-radius:50px; color: white; padding: 8px 20px; margin-left: 10px; text-align: center; text-decoration: none; display: inline-block; font-style: arial; font-size: 12px; }.compositions p:hover{ font-weight: bold; }
 <,DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1"> <title>InteractiveWebsite</title> <script src="../libraries/p5.js"></script> <script src="../libraries/p5.dom.js"></script> <script src="../libraries/p5.sound.js"></script> <.--script src="../libraries/Tone.js"></script--> <.--CreateJS libraries--> <script src="../libraries/soundjs.min.js"></script> <script src="../libraries/cordovaaudioplugin.min.js"></script> <script src="../libraries/flashaudioplugin.min.js"></script> <script src="../libraries/preloadjs.min,js"></script> <!--Own javascript files--> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <main> <div class="compositions"> <p id=Element1>Element 1</p><br> <p id=Element2>Element 2</p><br> <p id=Element3>Element 3</p><br> <p id=Element4>Element 4</p><br> <p id=Element5>Element 5</p><br> </div> </main> <script src="sketch.js"></script> <noscript>Sorry, your browser does not support JavaScript!</noscript> </body> </html>

I looked into two other topics ( here and here ), but they didn't seem applicable for my situation.我研究了另外两个主题( 此处此处),但它们似乎不适用于我的情况。

Thanks in advance, Mustard Shaper在此先感谢,芥末造型师

You face a closure problem, title is not declared您面临关闭问题,未声明标题

window.onload = () => {
    elements.forEach(element => {
        title = document.getElementById(element.title);
        //add event listeners
        title.addEventListener("mouseover", handleMouseOver = () => {
            mouseOver(title);
        });
        title.addEventListener("mouseout", handleMouseOut = () => {
            mouseOut(title);
        });
    });
}

So the 'default declaration' seems to be outside of the forEach.所以“默认声明”似乎在 forEach 之外。 Just declare it like const title = document.getElementById(element.title);只需将其声明为const title = document.getElementById(element.title); and everything will work.一切都会奏效。

Also add quote to id attribute like还将引号添加到 id 属性,例如

            <p id='Element1'>Element 1</p><br>

This is not part of your bug but just a small mistake这不是您的错误的一部分,而只是一个小错误

Edition

As you can see, it works如您所见,它有效

 const elements = [ {title: 'Element1'}, {title: 'Element2'}, {title: 'Element3'}, {title: 'Element4'}, {title: 'Element5'} ]; window.onload = () => { elements.forEach(element => { const title = document.getElementById(element.title); //add event listeners title.addEventListener("mouseover", handleMouseOver = () => { mouseOver(title); }); title.addEventListener("mouseout", handleMouseOut = () => { mouseOut(title); }); }); }; //play soundfiles const mouseOver = (title) => { title.style.backgroundColor = "red"; }; const mouseOut = (title) => { title.style.backgroundColor = "#4CAF50"; };
 body { margin:0; margin-left:0em; padding:0; overflow: hidden; } canvas { margin:auto; }.compositions { display: inline-block; align-items: center; font-style: arial; font-size: 17px; list-style-type: none; text-align: center; margin-top: 5em; }.compositions p { margin-bottom: 0.8em; margin:0em 0.8em 1em 1em; display: inline-block; }.compositions input { background-color: #4CAF50; /* Green */ border: none; border-radius:50px; color: white; padding: 8px 20px; margin-left: 10px; text-align: center; text-decoration: none; display: inline-block; font-style: arial; font-size: 12px; }.compositions p:hover{ font-weight: bold; }
 <,DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1"> <title>InteractiveWebsite</title> <script src="../libraries/p5.js"></script> <script src="../libraries/p5.dom.js"></script> <script src="../libraries/p5.sound.js"></script> <.--script src="../libraries/Tone.js"></script--> <.--CreateJS libraries--> <script src="../libraries/soundjs.min.js"></script> <script src="../libraries/cordovaaudioplugin.min.js"></script> <script src="../libraries/flashaudioplugin.min.js"></script> <script src="../libraries/preloadjs.min,js"></script> <!--Own javascript files--> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <main> <div class="compositions"> <p id='Element1'>Element 1</p><br> <p id='Element2'>Element 2</p><br> <p id='Element3'>Element 3</p><br> <p id='Element4'>Element 4</p><br> <p id='Element5'>Element 5</p><br> </div> </main> <script src="sketch.js"></script> <noscript>Sorry, your browser does not support JavaScript!</noscript> </body> </html>

I understand that you need to play audio files later, but that is an awful lot of work when you could probably just solve the problem with CSS .我知道您稍后需要播放音频文件,但是当您可能只用 CSS 解决问题时,这是一项非常艰巨的工作。 In general, you don't want to do with JavaScript what you can do with CSS.一般来说,你不想用 JavaScript 做你可以用 CSS 做的事情。 Save JavaScript for things you can't do with CSS.将 JavaScript 保存为 CSS 无法完成的事情。

p {
  background-color: #4CAF50;
}
p:hover {
  background-color: red;
}

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

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