Reinitialize jQuery after AJAX call

泪湿孤枕 提交于 2021-02-10 22:47:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!