简体   繁体   中英

Passing loop variable as argument in element function

Forgive the title, wasn't sure what to put.

I have some code like:

var links=document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
    var cur=links[i];
    cur.onmouseover=function(){alert(i);};
}

I remember seeing something like this before, but I have no clue how I would go about finding it. If another question like this has been asked, I would be far from surprised and would appreciate the link.

edit: the problem is that it always alerts what 'i' is after the loop finishes. If there are two links, they all alert 2.

edit: I remembered seeing it here: http://nathansjslessons.appspot.com/ . Great few lessons, I suggest anyone who hasn't already to do them.

Try this:

var links=document.getElementsByTagName('a'); 
for(var i=0;i<links.length;i++){     
    var cur=links[i];     
    cur.onmouseover=function(a){
        return function(){
            alert(a);
        }
    }(i); 
} 

You can actually use Array.forEach :

var links=document.getElementsByTagName('a'); 
[].forEach.call(links, function(cur, i) {
    cur.onmouseover = function() { alert(i); };
})

The trick is using .call() , passing links as the this parameter.

You'll need to add .forEach() for older browsers that don't support it natively.

This is a more reusable solution. remember the 3 r's reduce reuse recycle ;) it overflows into real life. see which is quickest optimization fun! http://jsperf.com/speed-test-for-links-script

var links       = document.getElementsByTagName('a'); 
var linksLength = document.getElementsByTagName('a').length //cache the length means quicker for loop

var addMouseOver = function(i){
    links[i].onmouseover=function(){
        alert(i);
    };
} //extract the function

for(var i=0;i<linksLength;i++){     
    addMouseOver(i);
} 

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