1

Here is a jsFiddle to explain my problem. If you try to click on the button "Add an ingredient", the button click event is called. My problem is that when I click on the "Create a subtitle", it dynamically created "Add an ingredient" button for each sub-categories. All button have the same id beginning with "create-ingredient" concatenated with a unique ID so it creates a unique ID for the button. I then use a "start with" selector in jQuery to select all button that start with "create-ingredient". It just doesn't select the ones that are dynamically created, it just work with the one that was originally in the html page.

Here is the click event not firing up on the dynamic ones:

$("[name^='create-ingredient']").click(function() {
    alert('ingredient clicked');
    return false;
});​

What do I need to change so the dynamically created button event gets called?

Thanks!

4

2 回答 2

6

click wires up the event statically. You want on, which triggers the event even on added elements.

Note that the syntax for on is slightly different than click. You typically use:

$("container").on("click", "selector", handler);

where "container" selects a static container element (can just be "document"), and "selector" is the element you want to target.

Forked Fiddle.


Edit

Clarifying the above per David's comment: the use of on actually attaches an event handler to "container", and delegates the callback to any elements inside the container that match "selector". This is a case where it's well worth reading the JQuery docs:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

于 2012-12-12T01:39:56.063 回答
2

Try: jQuery (>1.7 )

$(document).on('click', '[name^="create-ingredient"]', function() {
    alert('ingredient clicked');
    return false;
});

Or for older jquery (<1.7)

$("[name^='create-ingredient']").live(function() {
    alert('ingredient clicked');
    return false;
});
于 2012-12-12T01:40:51.570 回答