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++;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With