";document.getElementById onmouseover和函数";并没有如所希望的
" document.getElementById onmouseover and function " does not behave as wished × 108641
在这个函数中,它应该为菜单项(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
将分别为10
和10 % 4 = 2
。数组的索引#2是'pink'
。
要确保i
是触发mouseover和mouseout事件时所需的值,请将它们封装在函数中。
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));
}
}
这里有一个可能有帮助的解释:匿名函数中的变量
相关文章:
- 为什么使用AWS Signature v4对S3的REST调用并没有真正使用签名过程
- PhantomJS并没有在每次加载页面时进行所有AJAX调用
- 我的自动完成并没有暗示什么
- 取出图像标签alt:丢失"没有alt-id的图像标签是优选的并且不显示丢失的“;
- 世界的时钟并没有滴答作响
- 因果报应并没有执行测试用例
- $.ajax中的成功并没有被执行
- Mozilla并没有完美地执行这段代码,尽管它适用于Chrome和IE
- Rally App SDK 2.0:Ext.Element 方法“不可选择”并没有那么规范化
- 函数将信息返回到控制台日志,但实际上并没有执行应有的操作
- 扶手并没有填满表格
- Javascript似乎并没有取消隐藏我的元素
- 滑雪者并没有做出反应
- React路由帮助路由实际上并没有跳转到页面
- 元素维度正在DOM中更新,但更改并没有发生;t在调整大小时显示
- 敲除可观察数组并没有更新从数组中移除元素的视图
- javascript(prototype)if元素并没有属性
- Div元素并没有引导点击以启用拖动功能
- "下一个“;按钮并没有按预期循环浏览答案
- Reset()和class=“”;btn大蒜自动保存"type=“;重置”;实际上并没有重新设定窗体