learner
learner

Reputation: 41

jquery function within loop not iterating

I have a problem with my code, the title attribute only shows 16 rather than showing all values from 1 through 15. Why is this so can anyone suggest what I am doing wrong???

My Code

 x=1;
 while(x <= 15)
 {
     $("td#id"+x).mouseover(function(x){
     $(this).attr('title', x)           
   });
   x++;
}

Upvotes: 2

Views: 180

Answers (2)

Alnitak
Alnitak

Reputation: 339786

This is the very common "using a loop variable in a callback" problem.

As you're using jQuery the simplest fix is a data parameter to the handler:

 var x=1;
 while (x <= 15) {
     $("td#id"+x).mouseover({ x: x }, function(ev) {
         this.title = ev.data.x;        
     });
     x++;
 }

That said, why are you only setting this in a mouseover function? The title should be added to the elements directly, just once:

for (var x = 1; x <= 15; ++x) {
    document.getElementById('id' + x).title = x;
}

Doing it in a mouseover handler won't actually break anything, but it means you've registered an event handler that will be invoked (and update the DOM) over and over every time you move from one cell to another.

Upvotes: 9

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

The function you provide to jquery as event handler keeps a pointer to the outside block in which it was defined and to its (living) variables. That's how closure work.

So when it is executed, x is 15.

I know that most javascript developers don't know how that works, but that's a very interesting thing to know : http://jibbering.com/faq/notes/closures/

EDIT : I won't add here the usual fix I intended to add as Alnitak pointed before me the fact that a callback was, in fact, totally useless in that case ;)

Upvotes: 1

Related Questions