gpt4 book ai didi

javascript - "document.getElementById onmouseover and function "行为不尽如人意×108641

转载 作者:行者123 更新时间:2023-11-30 18:42:11 25 4
gpt4 key购买 nike

在这个函数中,它应该给菜单项 (li's) 一个数组中的特定背景 (png)。然而;它没有。它为所有 li 提供了名为“蓝色”颜色的背景 :(。你看到问题了吗?

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];

function MenuColorChange() {
for (var i = 0; i <= 10 ; i++) {
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() {
this.style.backgroundImage= "url(images/" + backgrounds[(i % backgrounds.length)] + ".png)";
}
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
this.style.background = 'none';
MenuActiveColor();
}
}
}

HTML:

        <ul>
<li id="custom-menu-item-id-1">
<a href="#">
Home
</a>
</li>
/* And 3 li's more... */
</ul>

最佳答案

onmouseover 使用的函数是外部函数的闭包,在执行时所有 onmouseover 处理程序的保存值为 i,实现你所看到的想要做的事情:

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];
function MenuColorChange() {
for (var i = 0; i <= 10 ; i++) {
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = (function(valueOfI){ return function() {
this.style.backgroundImage= "url(images/" + backgrounds[(valueOfI % backgrounds.length)] + ".png)";
}; })(i);
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
this.style.background = 'none';
MenuActiveColor();
}
}
}

关于javascript - "document.getElementById onmouseover and function "行为不尽如人意×108641,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6552047/

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