views:

28

answers:

2

I create li elements dynamically:

<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
[...]
</ul>

li_id is an array value which returns li id (=1,2,3...)

How can I bind different functions to every li element in code like this:

for (li_id in lids)
{
console.log(li_id);                         
$(li_id).bind('mouseover', function() {
console.log(li_id);
});
}

The above doesn't work. How to write it properly?

With live() instead of bind() it shows the id of the last element of the lids array, not 1,2,3...[...], like the console.log() outside the $ statement...

+1  A: 

http://www.mennovanslooten.nl/blog/post/62

or

http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example

Given your HTML, the code can be written in two ways.

Using jQuery 1.4 Event.data parameter:

var lids = [1,2,3];
for (i in lids) {
    var li_id = lids[i];

    $('#' + li_id).bind('mouseover', { id: li_id }, function(ev) {
        console.log(ev.data.id);
    });
}

Or, creating a closure with anonymous function:

var lids = [1,2,3];
for (i in lids) {
    var li_id = lids[i];

    // an anonymous function 
    (function (id) {
        $('#' + id).bind('mouseover', function() {
            console.log(id);
        });        
    })(li_id); // ...called every time with different id

}

I prefer jQuery Event.data way in this instance.

Marko Dumic
THX!I think that is what I was looking for. But could you show me how to implement this into my code:)?
domi
I added sample code.
Marko Dumic
A: 

So with closure the correct answer would be:

$(li_id).bind('mouseover', function(val) { 
                             return function() { 
                                console.log(val); 
                             } 
                           }(li_id));

But this is only required if you need to pass the value of the loop into the function.

Joshua
The selector is minor problem. Merely a typo. The closure problem is more serious one.
Marko Dumic
Thanks Marko, actually I see that now. I've wrestled with that myself a couple of times so this actually helps me as well. Thanks!
Joshua