简体   繁体   English

在AJAX加载的DOM元素上运行jQuery脚本

[英]Running jQuery scripts on DOM elements loaded with AJAX

I understand that jQuery will not run when the DOM content is being loaded via AJAX. 我了解通过AJAX加载DOM内容时jQuery将无法运行。 But I'm confused as to the reason why. 但是我对原因感到困惑。 My understanding was that the DOM elements didn't exist at the time the jQuery was initiated therefore it won't find the correct IDs or classes. 我的理解是,在jQuery启动时DOM元素不存在,因此无法找到正确的ID或类。

But I have a situation where the jQuery is only called AFTER all the content has been loaded via AJAX. 但是我有一种情况,所有内容都已通过AJAX加载之后,jQuery仅被称为。 yet it still does not work. 但是它仍然不起作用。

Here is my code. 这是我的代码。 I am trying to get the function decorateGains() to run after AJAX completes. 我试图让函数decorateGains()在AJAX完成后运行。

loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
    else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.onreadystatechange=function()
      {
        if (xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("home-table").innerHTML=xmlhttp.responseText;}
      }
    xmlhttp.open("GET","actions/get-data-"+type+".php",true);
    xmlhttp.send();
    decorateGains();
}

You can see that I am including a call to the function decorateGains() right at the end of the loadData() function. 您可以看到我在loadData()函数末尾包含了对函数decorateGains() loadData()调用。

The decorateGains() function does run, as I can see my console message. 如我所见,控制台中的decorateGains()函数确实运行。 However it does not do the task that it should. 但是,它没有完成应有的任务。

function decorateGains() {
    console.log('here');
    $(".gains").each(function() { 
        var num = +($(this).text());
        if (num > 0) {
            console.log('here');
            $(this).addClass("positive");
        }
        if (num < 0) {
            console.log('here');
            $(this).addClass("negative");
        }
    });
}

(The script searches for all elements with a class of .gains and adds a new class of positive or negative depending on the content of the element. Essentially it decorates the .gains element to be red or green depending on whether the number is negative or positive). (脚本会搜索所有带有.gains类的元素,并根据元素的内容添加新的positivenegative类。基本上,它会根据数字是负数还是绿色将.gains元素修饰为红色或绿色。正)。

This is because the AJAX call is asynchronous. 这是因为AJAX调用是异步的。 The request has not been completed (and therefore the new content has not been appended to the DOM) when you call your decorateGains() function. 当您调用decorateGains()函数时,请求尚未完成(因此新内容尚未添加到DOM)。 You need to place the call to the function inside the onreadystatechange handler, after setting the innerHTML : 在设置innerHTML之后,您需要将对函数的调用置于onreadystatechange处理函数内:

loadData('7-days'); // Runs the default AJAX for 7 days
function loadData(type) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("home-table").innerHTML = xmlhttp.responseText;

            decorateGains(); // <-- move this in here
        }
    }
    xmlhttp.open("GET", "actions/get-data-" + type + ".php", true);
    xmlhttp.send();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM