ThePhi
ThePhi

Reputation: 2611

Javascript closures : Loop inside Loop

I already know how to loop thanks to closure like this :

for (var i = first; i <= last; i++) {
    document.getElementById(more + i).onmouseover = (function(arg1) {
        return function() {
            document.getElementById(arg1).style.display = "block";
        }
    })(i);
}

But I'd like now to do a look inside the loop. I've got elements of the DOM which must be dynamically attached to other elements. The elements are of the type: '1text1', '1text2', '1text3',... and '2text1', '2text2', '2text3', '3text4'... I've tried something like this:

var text;
var ktext;
for (var k = 1; k <= last_number; k++) {
    for (var i = first; i <= last; i++) {
        ktext = k + text;
        document.getElementById(ktext + i).onmouseover = (function(arg1, arg2) {
            return function() {
                document.getElementById(arg1 + arg2).style.display = "block";
            }
        })(ktext, i);
    }
}

But the loop is partially lost. If I put alert(ktext + i) just at the beginning of the var i loop, I see: 1text1, 1text2, 1text3, 1text4 then 2text1 (as expected), but not 2text2, 2text3... as if the second pass of the var k loop stops too early.

Upvotes: 0

Views: 179

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Your use of closures is unnecessary:

for( k=1; k<=last_number; k++) {
  for( i=first; i<=last; i++) {
    document.getElementById(k+text+i).onmouseover = function() {
      this.style.display = "block";
    }
  }
}

Anyway, your loop may be stopping early if one of the elements doesn't exist on the page. You should check for the element's existence before attempting to assign to it.

Upvotes: 2

Related Questions