gpt4 book ai didi

javascript - 在 For 循环中添加事件监听器

转载 作者:行者123 更新时间:2023-12-02 23:27:54 24 4
gpt4 key购买 nike

我正在尝试使用以下方法在 for 循环内添加事件监听器“mouseover”:

<!DOCTYPE html>
<html>
<head>
<title>BUTTONS</title>
</head>
<body>
<button>BUTTON 1</button>
<button>BUTTON 2</button>
<script type="text/javascript">
var buttons = document.querySelectorAll("button");
for(i=0;i<buttons.length;i++){
buttons[i].addEventListener("mouseover",function(){
this.style.backgroundColor = "gray";
});
}
</script>
</body>
</html>

值得庆幸的是,它运行良好。我尝试不使用“this”关键字来试验代码

<!DOCTYPE html>
<html>
<head>
<title>BUTTONS</title>
</head>
<body>
<button>BUTTON 1</button>
<button>BUTTON 2</button>
<script type="text/javascript">
var buttons = document.querySelectorAll("button");
for(i=0;i<buttons.length;i++){
buttons[i].addEventListener("mouseover",function(){
buttons[i].style.backgroundColor = "gray";
});
}
</script>
</body>
</html>

因为我认为在 for 循环中,所有内容都会被翻译为

buttons[0].addEventListener("mouseover",function(){
buttons[0].style.backgroundColor = "gray";
});

buttons[1].addEventListener("mouseover",function(){
buttons[1].style.backgroundColor = "gray";
});

应该可以正常工作。然而,并没有,为什么?

最佳答案

for 循环中使用 let 声明变量这将创建一个 block 范围局部变量。这将确保 i 值在每次迭代中都能正确保留。

<button>BUTTON 1</button>
<button>BUTTON 2</button>
<script type="text/javascript">
var buttons = document.querySelectorAll("button");
for(let i=0;i<buttons.length;i++){
buttons[i].addEventListener("mouseover",function(){
buttons[i].style.backgroundColor = "gray";
});
}
</script>

关于javascript - 在 For 循环中添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56651842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com