一段时间以来一直在努力解决 Javascript 闭包问题,试图将大脑包裹在函数范围内,但我认为它们正在包裹着我。我看过很多帖子(Nyman 的帖子最有帮助),但显然还是不明白。尝试在 jQuery 中的悬停方法上运行循环。需要悬停功能来最终触发一个以上的动作,但现在很高兴让它们使用单个图像交换。
$(document).ready(function() {
imageSource = [];
imageSource[0] = 'images/img0.png' //load 0 position with "empty" png
imgArea = [];
for (var i=1; i<11; i++) {
(function( ){ //anonymous function for scope
imageSource[i] = 'images/img' + i + '.png';
imgArea[i] = '#areamap_Img' + i;
// running console.log here gives expected values for both
$(imgArea[i]).hover( //imgArea[i] (selector) works correctly here
function() {
$('#imgSwap').attr('src',imageSource[i]); // imageSource[i] is undefined here
},
function() {
$('#imgSwap').attr('src','images/img0.png');
});
})(); // end anonymous function and execute
}; // for loop
});
尝试使用匿名函数从另一个 jQuery 帖子中确定范围的想法。似乎工作正常,但在第一个悬停函数中为数组值抛出了一个未定义的值,我猜是因为它是一个内部函数(硬编码的图像源在那里正常工作)。