";document.getElementById onmouseover和函数";并没有如所希望的

" document.getElementById onmouseover and function " does not behave as wished × 108641

本文关键字:quot 并没有 所希望 onmouseover document getElementById 函数      更新时间:2023-09-26

在这个函数中,它应该为菜单项(li(提供一个数组中的特定背景(png(。然而事实并非如此。它给所有李的背景颜色叫做蓝色。你看到问题了吗?

//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();
        }
    }
}

这让我很惊讶。我希望它能让所有的背景都变成粉红色。发生这种情况的原因是,当您实际将鼠标悬停在任何<li>元素上时,i将分别为1010 % 4 = 2。数组的索引#2是'pink'

要确保i是触发mouseovermouseout事件时所需的值,请将它们封装在函数中。

function MenuColorChange() {
    for (var i = 0; i <= 10 ; i++) {
        (function(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();
            }
        }(i));
    }
}

这里有一个可能有帮助的解释:匿名函数中的变量