gpt4 book ai didi

jQuery 和闭包

转载 作者:行者123 更新时间:2023-12-01 07:03:09 25 4
gpt4 key购买 nike

我的页面上有多个菜单,它们都使用相同的鼠标悬停和单击事件,因此我决定将其放入一个函数中。然而,变量似乎总是被分配给悬停(函数,函数)函数的最后一个参数。

$(document).ready( function() {
menuMouseOver = function() {
for(i=0, u=arguments.length; i<u; i++){
var parent = arguments[i].parent;
var active = arguments[i].active;
var childSelect = arguments[i].childSelect;
console.log(active); //logs the correct active
$(parent).children(childSelect)
.not('.'+active).each( function(i, e) {console.log(active);})
//The above console.log logs the correct active
.hover( function() {
console.log(active); //this one always logs menu2_active
$(this).addClass(active);
}, function() {
$(this).removeClass(active);
});
}
}
menuMouseOver( { parent: '#menu1',
active: 'menu1_active',
childSelect: ':gt(0)'},
{ parent: '#menu2',
active: 'menu2_active',
childSelect: ':gt(0)'});
});

为什么最后一个 console.log 将始终记录最后一个 active,而不是属于arguments[i].active 的日志。 (在此示例中,它始终记录参数[1].active 的 active)我究竟做错了什么?

而且,实际功能更复杂,但问题也存在于这个变体中。

最佳答案

JavaScript 没有 block 作用域,因此您在 for 循环中声明的变量的值在每次迭代时都会更改,并且所有这些函数都引用相同的变量。诀窍是在 for 循环中创建一个新的函数作用域,以便在该迭代期间绑定(bind)您声明的变量。

您可以通过在循环内执行匿名函数来完成此操作:

menuMouseOver = function() {
for(i=0, u=arguments.length; i<u; i++){
(function(){ // anonymous function to create new scope
var parent = arguments[i].parent;
var active = arguments[i].active;
var childSelect = arguments[i].childSelect;
console.log(active); //logs the correct active
$(parent).children(childSelect)
.not('.'+active).each( function(i, e) {console.log(active);})
//The above console.log logs the correct active
.hover( function() {
console.log(active); //this one always logs menu2_active
$(this).addClass(active);
}, function() {
$(this).removeClass(active);
});
})(); // execute the anonymous function
}
}

按照之前的方式,所有函数都通过相同的变量引用关闭,因此使用最后一个值,而不是创建函数时的值。使用函数作用域将使其按照您的预期运行。

关于jQuery 和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492580/

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