dave
dave

Reputation: 1679

javascript for loop, jquery id generation and recognition

var product=""; for (var i=0; i<10; i++) { product+=""+i+""; $("#"+i).hover(function() { alert(i); }); }

product variable is able to generate the desired output with the div ids ,but when I m moving my mouseover those divs, that mouseover function(from jquery) is not working/called.

Please help

Thanks Dave

Upvotes: 0

Views: 551

Answers (3)

Felix Kling
Felix Kling

Reputation: 816422

Why not do it like this:

for (var i=0; i<10; i++)
{
    $("<div align='center' width='88' />")
    .text(i)
    .attr('id', 'id' + i)
    .bind('mouseenter mouseleave', {counter: i}, function()
    {
        alert(event.data.counter);
    })
    .attachTo(someDOMNode);
}

A few comments:

  • IDs must not start with a digit
  • Be careful when creating closures in a loop, because the loop variable i will have the value from the last iteration in any closure (i.e. every alert(i) will alert 10) (See JavaScript Closures for Dummies - Example 5). That is why I use bind() here. The events mouseenter and mouseleave are the ones, hover() binds the handler to. And to overcome the problem with i, I pass the value of i as event data.

Upvotes: 1

sushil bharwani
sushil bharwani

Reputation: 30187

I am wondering that if in your code where the DIV string has been attached to DOM. I believe there is some code where you have done this.

Upvotes: 1

amphetamachine
amphetamachine

Reputation: 30595

You problem is that product isn't part of the DOM when you try to assign a function to it. $("#"+i) will return an empty list.

Upvotes: 2

Related Questions