Simple question, since version 1.7 of jQuery .live() has been deprecated in favor of .on(); however .on() does not seem to work on elements that are rendered via JavaScript and loaded into the DOM. So my question is, should .live() still be used or how would .on() capture these newly generated elements?
As an example, here's my code:
$("#listitem").append("<li id='removeitem'>" +
formdata + ' <a href="#">Remove</a></li>');
And when I try to operate on this element via .on() - the result is nothing, whereas .live() is able to grab this element.
$("#removeitem").live("click", function(event) { alert($(this).text()); });
live
version:
$("#removeitem").live("click", function(event) { alert($(this).text()); });
should be changed to:
$("#containerId").on("click", "#removeitem", function(event) {
alert($(this).text());
});
Where containerId
is the static element that the removeitem
is loaded into.
You can simply use body
as the static element:
$("body").on('click', '#removeitem'm fn);
But the code will be less efficient, just try with it to show how it works.
Notes:
id
because it's invalid markup.listitem
is the static element in your code.Update:
Maybe that's my problem - I just replaced .live with .on
You can't simply replace them... They work in other ways, and have different parameters!
Read the docs for each function:
on
:
.on(events [, selector] [, data], handler(eventObject))
.live( events, handler(eventObject) )