开发者

Question of Javascript scope within a loop [duplicate]

开发者 https://www.devze.com 2023-04-06 04:29 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Javascript closure inside loops - simple practical example
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Javascript closure inside loops - simple practical example

I am (quite obviously) a beginner in javascript. I am attempting to understand why, when using a for loop and calling an event handler ala

http://jsfiddle.net/Yw5Uj/

var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');
var content = document.getElementById('content');
var contentSections = content.getElementsByTagName('div');


for(i =0; i < contentSections.length; i++) {
    contentSections[i].style.display = 'none';
}

for(i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = function() {
         contentSections[i-1].style.display = 'block'
    }
}

I only get the last iteration of the loop. How would I call a function to act on each of the links in the navLinks array as they are moused over?

There are many questions on this, but often times they are a bit too complica开发者_运维问答ted for me to understand.


Try the following

var makeFunction = function(i) {
  return function() { contentSections[i-1].style.display = 'block'; };
};

for(var i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = makeFunction(i);
}

What's throwing you off is the lifetime semantics of i. In Javascript there is only one i defined for the current function (and without the use of var it's likely in the global scope). So every function assigned to onmouseover is using the same i variable which has the final value of navLinks.length.

My solution works because it uses function scope to create a new i for every iteration of the loop.


Updated example here.

function handleMouseOver(i) {
    return function () {
        for (var j = 0; j < navLinks.length; j++) {
            contentSections[j].style.display = 'none';
        }
        contentSections[i].style.display = 'block';
    }
}

for(i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = handleMouseOver(i);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消