Search code examples
jquerydynamic-rebinding

Bind different functions for just created li elements


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


Solution

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

    or

    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.