2

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++;
}
1
  • this is part of bigger script, the coulmns of table are dynamically generated and has id's assigned, the title attribute will have the value of x , which is the iterator, so if e.g <td id=1 title="1">someval</td> <td id=2 title="2">someval</td> .... <td id=15 title="15">someval</td> Commented Jun 1, 2012 at 18:14

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

6 Comments

You amaze me with simplicity +1
Event data should go first :)
thanks..it took you one second to resolve a problem that I struggled for more than an hours.Thanks once again...
@learner What you are doing doesn't make much sense. I think it can done differently, in a better way if you can give us little more details. (edit: Look at the later part of this post)
learner : read about closures. Javascript is a very different world when you understand them.
|
1

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.