.on Click for a dynamically created item

114 Views Asked by At

I am appending a <li> and when I try to click it using the new .on event, it doesn't work. I don't want to use the .live event since it might be going to be deprecated in the future.

Here is my example: http://jsfiddle.net/2Lbbe/

This works for the first item, if you create a new the alert doesn't work.

Anyone know how can I solve this problem without using live?

2

There are 2 best solutions below

0
On BEST ANSWER

You're quite close, all you need to do is change your selector setup:

From

$("#bxs li").on('click',function() {

To

$("#bxs").on('click', 'li',function() {

Here's an update to your jsfiddle: http://jsfiddle.net/jasper/2Lbbe/2/

Using the .on() function like this is the same as the old .delegate() function:

$(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(elements).on(events, selector, data, handler);        // jQuery 1.7+
0
On

You are essentially trying to do what used to be called .delegate(). Attach the event handler to something permanent, then look inside for your targets.

$("#bxs").on('click', 'li',function() {

your updated fiddle

From the docs:

.on( events [, selector] [, data] , handler )

Description: Attach an event handler function for one or more events to the selected elements.

.on() is now capable of serving the purpose of .bind() .live() and .delegate() depending on how it is used. If you want a handler to apply to future items you have to make the final selection using the optional [,selector]