Reputation: 5180
In JavaScript/jQuery, if I want to have a function that can run on an element that has been appended to the DOM, it has to be created after the element has been appended to the DOM. How can I do this? I heard one can do this with the jQuery .on()
function, but I'm not quite sure how.
HTML:
<span>Hello Stackoverflow</span>
JavaScript:
$("span").click(function () {
addMyElement();
});
$("p").click(function () {
removeMyElement(this);
});
function addMyElement() {
$("<p>Hello World</p>").appendTo("body");
}
function removeMyElement(myElement) {
$(myElement).remove();
}
Example on jsFiddle.net.
Upvotes: 1
Views: 659
Reputation: 6359
function addMyElement() {
$("<p>Hello World</p>").appendTo("body").click(function () {
removeMyElement(this);
});
}
Will work for you, not hugely readable with all that chaining though.
Upvotes: -2
Reputation: 145388
This is called delegated-events approach and it works as follows:
$("body").on("click", "p", function () {
// ...
});
Instead of body
you can use any parent element of p
.
DEMO: http://jsfiddle.net/wWXrK/6/
Upvotes: 7