Adding an event handler to a newly created item

I am trying to add a new item to the order list with a link to delete it:

$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

but this does not work:

$('a[href^="#remove"]').on('click', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

Any idea why?

+5
source share
2 answers

Create a new element in jQuery tags and apply an event handler at this time. This is a cleaner and more efficient approach than using several complex jQuery selectors to assign an event handler after an element has already been inserted into the DOM:

//this line will create your element in memory, but not insert it to the DOM
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

//you can apply jQuery style event handlers at this point
newElmt.on('click',function(e) {

    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

//insert the element as you were before
$('#list ol').append(newElmt);
+8
source
$('#list').on('click', 'a[href^="#remove"]', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

As you add lidynamically, so you need to delegate event processing using .on()as a delegate handler.

0
source

All Articles