问题
I'm having a problem where after dynamically populating an element via AJAX, my jQuery functions aren't working on the new content.
I have a list of files for example that is populated when hitting a "refresh" button. I want to display an alert with the filename when double clicking the item in the list. Each item has the "file" class.
I'm using this code:
$('.file').on('dblclick', function(event){
alert($(this).html());
});
This works for any elements that are there in the first place, but not after the AJAX call.
This is a school assignment and I'm required to use regular Javascript AJAX methods, rather than the built-in jQuery AJAX functionality. I'm guessing this is the problem and the reason that jQuery is not noticing the newly populated elements.
The refresh button is calling this function:
function getFileList()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("files").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filelist.php",true);
xmlhttp.send();
}
How can I get jQuery to notice these new elements properly if I'm being forced to use regular JS for the AJAX calls as opposed to jQuery's AJAX methods?
回答1:
The problem is that you are only attaching .on() to the ".file" elements that exist initially. You just need to attach the .on() to the document and supply the selector as an option. e.g.
$(document).on('dblclick', '.file', function(event){
alert($(this).html());
});
That way the event will be attached to future elements of class "file".
回答2:
jQuery.on
bind to elements already in the DOM. If you need bind to future elements, you can use jQuery.live
or unbind and rebind with jQuery.on
again. The former is easier.
$('.file').live('dblclick', function(event){
alert($(this).html());
});
EDIT: As mentioned, live
is deprecated and slow. Always prefer on
.
来源:https://stackoverflow.com/questions/13517592/reinitialize-jquery-after-ajax-call