Reputation: 5
my simple script is append few elements through jquery .
what im trying to do is to add some ajax call for those created elements .
the issue is the event never work for those elements and i tried a lot of Jquery methods but all fail .
$("#currentbuild").append('<li class="cancelevent"></li>');
$('.cancelevent').bind("click",function(e) {
var eventid = $(this).attr('id');
e.preventDefault();
alert(eventid);
})
also i tried
$("#currentbuild").append('<li class="cancelevent"></li>');
$('.cancelevent').on("click",function(e) {
var eventid = $(this).attr('id');
e.preventDefault();
alert(eventid);
})
but it never show up anything
Upvotes: 0
Views: 43
Reputation: 8640
You have it almost correct:
$("#currentbuild").append('<li class="cancelevent"></li>');
$('#currentbuild').on("click",".cancelevent",function(e) {
var eventid = $(this).attr('id');
e.preventDefault();
alert(eventid);
});
This adds a click
handler to #currentbuild
(which is not dynamic and therefore always in the DOM). However, instead of reacting to a click on itself, it only listens to clicks inside itself and only to elements that have a class of cancelevent
. And since you don't add a click handler to an element that may be added and/or removed dynamically, the handler will always be there.
EDIT: As @tcovo points out in the comments below, your code should work as you posted it here. I assume this is not exactly your code and the append
happens dynamically as the result of another event handler (and not on page load as you suggest in your sample).
Also, var eventid = $(this).attr('id');
wouldn't work in your example either, because there is no id
attribute on the <li>
... Another reason I assume this is not the exact code that is giving you trouble. :)
Upvotes: 1