for (var i = 0; i < lists.length; i++) { lists[i].addEventListener('mouseover', function () { if (i == 0) { this.style.backgroundImage = 'url(img/最新b.jpg)'; } else if (i == 1) { this.style.backgroundImage = 'url(img/新闻b.jpg)'; } else if (i == 2) { this.style.backgroundImage = 'url(img/公告b.jpg)'; } else if (i == 3) { this.style.backgroundImage = 'url(img/正能量b.jpg)'; } else if (i == 4) { this.style.backgroundImage = 'url(img/攻略b.jpg)'; } else { this.style.backgroundImage = 'url(img/同人b.jpg)'; } }) }这段代码有啥问题
时间: 2024-02-14 08:05:42 浏览: 14
这段代码可能会出现问题,原因是因为在添加事件监听器时,使用了变量 i,但是当事件触发时,i 的值已经发生了变化,可能不是预期的值,导致代码出现错误。
为了避免这种问题,可以使用闭包来解决。可以将变量 i 作为参数传递给一个自执行函数,并将该函数作为事件监听器。这样在事件触发时,该函数中的 i 值就是预期的值,不会出现错误。修改后的代码如下:
```
for (var i = 0; i < lists.length; i++) {
(function(index) {
lists[index].addEventListener('mouseover', function () {
if (index == 0) {
this.style.backgroundImage = 'url(img/最新b.jpg)';
} else if (index == 1) {
this.style.backgroundImage = 'url(img/新闻b.jpg)';
} else if (index == 2) {
this.style.backgroundImage = 'url(img/公告b.jpg)';
} else if (index == 3) {
this.style.backgroundImage = 'url(img/正能量b.jpg)';
} else if (index == 4) {
this.style.backgroundImage = 'url(img/攻略b.jpg)';
} else {
this.style.backgroundImage = 'url(img/同人b.jpg)';
}
});
})(i);
}
```
这样就可以避免变量 i 带来的问题了。