I'm having some issues removing list items upon click after using jquery to add the list items. If I had to guess why this is happenings, it's because jquery might be looking at my original HTML document and not the updated one after adding list items? Either way, I can't figure out how to fix it.
Here is my HTML:
And my jQuery:
$(document).ready(function() {
$('#add').click(function() {
var item = $('#todo')
$('ul').prepend(""+item.val()+" ");
});
$('li').click(function() {
$(this).remove();
});
});
Answer
Since you trying to add event handlers for dynamically added elements you need to use event delegation
$(document).ready(function() {
$('#add').click(function() {
var item = $('#todo')
$('ul').prepend(""+item.val()+" ");
});
$('ul').on('click', 'li', function() {
$(this).remove();
});
});
Demo: Fiddle
No comments:
Post a Comment