简体   繁体   中英

Why doesn't the mouseover event work when use closure in Javascript?

I have the following code

<ul>
  <li>one</li>
  <li>two</li>        
  <li>three</li>
  <li>four</li>
</ul>

var lists = document.getElementsByTagName("li");

for(var i=0, len = lists.length; i< len; i++){
    lists[i].onmouseover = function(){
        console.log(i);
    }(i);
}

Expected result: when mouse over each li , I got 0 or 1 or 2 or 3 in the console, but I only got those number when refresh the page not in mouseover , anybody knows why?

The "calling parenthesis" (i) after the function expression execute the function immediately and assign its return value as event handler (which is undefined ). Here is an example with a function declaration, which makes it easier to see (hopefully):

function foo(i) {
    console.log(i);
}

// in the loop
lists[i].onmouseover = foo(i);

See how foo is called and the return value is assigned to lists[i].onmouseover ?

You have to return a function from the immediately invoked function expression:

lists[i].onmouseover = (function(i){
    return function() {
        console.log(i);
    };
}(i));

or with a function declaration:

function createHandler(i) {
    return function() {
        console.log(i);
    };
}

// in the loop
lists[i].onmouseover = createHandler(i);

More info: JavaScript closure inside loops – simple practical example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM