[英]hello, Why colorPicked is not return and just work in the EventListener
why colorPicked don't return from the function this happens also when I add return the console says it's not identified her is the html and js because I need to work with the colorPicked in outside of the function`为什么 colorPicked 不从 function 返回时也会发生这种情况
const mainColor = document.querySelector(".mainColor");
const colors = document.querySelector(".colors");
colors.addEventListener("click", (e) => {
colors.id = "dis";
const colorPicked = e.target.className;
mainColor.style.backgroundColor = colorPicked;
return colorPicked;
});
mainColor.addEventListener("click", () => {
switch (colors.id) {
case "dis":
colors.id = "";
break;
case "":
colors.id = "dis";
}
});
console.log(colorPicked);
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <link rel="stylesheet" href="./style.css" /> <title>Document</title> </head> <body> <div class="mainColor"></div> <div id="dis" class="colors"> <div class="#ee6633"></div> <div class="#ee3377"></div> <div class="#2ee8bb"></div> <div class="#ee3311"></div> <div class="#d208cc"></div> <div class="#16141c"></div> <div class="#dd1188"></div> <div class="#7e4071"></div> </div> <!-- Scripts --> <script src="sandbox.js"></script> </body> </html>
You can't log colorPicked variable because it's declared inside a function block, you can't access it from outside.您无法记录 colorPicked 变量,因为它是在 function 块内声明的,您无法从外部访问它。 Look at this example:
看这个例子:
const f = () => { let innerVar = 'demo'; return innerVar; } console.log(f()) console.log(innerVar)
Try this:尝试这个:
let colorPicked = ''; colors.addEventListener("click", (e) => { colors.id = "dis"; colorPicked = e.target.className; mainColor.style.backgroundColor = colorPicked; }); console.log(colorPicked);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.