Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
}
like image 527
learner Avatar asked Aug 09 '26 05:08

learner


1 Answers

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.

like image 91
Alnitak Avatar answered Aug 12 '26 04:08

Alnitak