Jquery click bindings are not working correctly when binding multiple copies

Posted by KallDrexx on Stack Overflow See other posts from Stack Overflow or by KallDrexx
Published on 2010-05-14T04:42:10Z Indexed on 2010/05/14 4:44 UTC
Read the original article Hit count: 254

Filed under:
|
|

I seem to have an issue when creating copies of a template and tying the .click() method to them properly. Take the following javascript for example:

        var list;

        // Loop through all of the objects
        var topics = data.objects;
        for (x = 0; x < objects.length; x++) {
            // Clone the object list item template
            var item = $("#object_item_list_template").clone();

            // Setup the click action and inner text for the link tag in the template
            var objectVal = objects[x].Value;
            item.find('a').click(function () { ShowObject(objectVal.valueOf(), 'T'); }).html(objects[x].Text);

            // add the html to the list
            if (list == undefined)
                list = item;
            else
                list.append(item.contents());
        }
        // Prepend the topics to the topic list
        $("#object_list").empty().append(list.contents());

The problem I am seeing with this is that no matter which item the user clicks on in the #object_list, ShowObject() is called with the last value of objectVal. So for example, if the 3rd item's <a> is clicked, ShowObject(5,'T'); is called even though objects[2].Value is successfully being seen as 2.

How can I get this to work?

The main purpose of this code is to take a variable number of items gotten from a JSON AJAX request, make copies of the item template, and insert those copies into the correct spot on the html page. I decided to do it this way so that I can keep all my HTML in one spot for when I need to change the layout or design of the page, and not have to hunt for the html code in the javascript.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript