作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用以下方法在 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/
我是一名优秀的程序员,十分优秀!