Yarin
Yarin

Reputation: 183859

When adding click handlers to list items in jQuery, they all trigger immediately

In the following code I'm rendering a list of projects, each item of which will perform an action relevant to its associated project object when clicked. However, when I run the code, the alerts all show up at once on page load, and then don't show up when the list item is clicked. What am I doing wrong?

var projects = (an array of project objects)

jQuery.each(projects, function(index, project) {
    jQuery("#project-list").append("<li "+classString+"><a>"+project.title+"</a></li>");
    jQuery("#project-list").find("li:last").click( function() {
                        alert(project.title);
                    });
    }); 

Upvotes: 1

Views: 503

Answers (2)

Sampson
Sampson

Reputation: 268434

I was able to whip up the following which does, to my knowledge, what you're attempting:

var projects = [{title:'Project 1'},{title:'Project 2'}];

$.each(projects, function(i){
  $("<a/>", { href:'#', text:projects[i].title })
    .click(function(e){alert( projects[i].title );})
    .wrap("<li></li>")
    .parent()
    .appendTo("#project-list");
});

I was merely guessing on the object structure for your projects, but you could modify this. I'm not sure why your clicks would have been happening automatically; mine work fine in the above code sample. Perhaps there's something else invoking them that isn't present in the code you posted here.

Online Demo: http://jsbin.com/uhixac/edit

Upvotes: 1

Tgr
Tgr

Reputation: 28200

I would suspect an extra pair of braces:

(...).click(function() {
    //...
}()); // note the extra braces here

This executes your click handler immediately and passes the return value (undefined) to jQuery.click (which triggers a simulated click event, doing nothing) instead of binding the click handler to the click event.

Upvotes: 1

Related Questions