I have appended content (using ajax) to my document and my events are not firing. I know this can be done using .live() but I read somewhere that it’s deprecated now?
This is my code (it works fine on document ready, but not on the newly appended items):
$('li[id^="inv-"] a.close').on('click', function(){
var item=($(this).closest("li[id^='inv-']")).attr('id');
var id = parseInt(item.replace("inv-", ""));
$.ajax({
type: "POST",
url: "ajax-invi.php",
dataType: "html",
data: "id="+idboda+"&idinv="+id+"&borrar=ok",
success: function(data) {
noty({"text":"El invitado ha sido borrado"});
$("body").find('li#inv-' + id).remove();
}
});
});
And the items:
<ul>
<li id="inv-39">
<div class="row_field">
<label>Adri</label>
<a class="close" href="#invlist">Borrar</a>
</div>
</li>
<li id="inv-40">
<div class="row_field">
<label>Marga</label>
<a class="close" href="#invlist">Borrar</a>
</div>
</li>
</ul>
try
in this way you delegate the event handling to the ul which is present when the DOM is loaded and handles the events of elements added through AJAX. If the ul is not present when the dom is loaded you could delegate to the
<body>tagEDIT – live() it’s actually a wrapper around
on()(before it was a wrapper arounddelegate()) but delegates the event handling usually to thewindowwhich means that the event has to bubble up a lot. Taken from jQuery source