views:

43

answers:

3

Hello friends,

var product="";
for (var i=0; i<10; i++)
{
    product+="<div align='center' width='88' id='"+i+"'>"+i+"</div>";
    $("#"+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

+2  A: 

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.

amphetamachine
Even with that it would not work properly because of the way the OP is generating the closure in the loop.
Felix Kling
+1  A: 

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.

sushil bharwani
+1  A: 

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.
Felix Kling