I'm trying to use 'click' on a dynamically generated DOM. I know that I can just use live or on, however my dynamically generated content is within multiple dynamically generated pieces of content and live/on no longer works.
So my code looks something like this but with more elements before El_b:
El_a = document.createElement("li");
El_b = document.createElement("a");
El_b.id = "myEl";
El_a.appendChild(El_b);
Is there a way to make this work?
PS: I've also tried the livequery jQuery plugin.
As far as delegation is concerned, you always have at least one static DOM element available to you, which is the document
. If you can't find a closer element to delegate to, delegate to this.
However, delegation seems to be unnecessary here. The entire process of creating your elements and attaching listeners could be condensed to:
var a = $("<li/>").append($("<a/>").attr("id", "myElement")).click(function () {
alert('hello');
});
If, as you say, you cannot change the object creation, you can still select it by its ID and attach the listener:
$('#myElement').click(function () {
alert('hello');
});
Also, those are document fragments , not documents proper, and certainly not DOMs.
If you want to bind a function on the click event on El_b, you can just do this :
$(El_b).click(function() {
// Your code here
});
But you can use on
i think. Even if you create multiple DOM elements. You can use the document
or the body
. Example :
$('body').on('click', 'li a.my_class', function() {
// Your code here
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.