繁体   English   中英

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

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

我了解通过AJAX加载DOM内容时jQuery将无法运行。 但是我对原因感到困惑。 我的理解是,在jQuery启动时DOM元素不存在,因此无法找到正确的ID或类。

但是我有一种情况,所有内容都已通过AJAX加载之后,jQuery仅被称为。 但是它仍然不起作用。

这是我的代码。 我试图让函数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();
}

您可以看到我在loadData()函数末尾包含了对函数decorateGains() loadData()调用。

如我所见,控制台中的decorateGains()函数确实运行。 但是,它没有完成应有的任务。

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");
        }
    });
}

(脚本会搜索所有带有.gains类的元素,并根据元素的内容添加新的positivenegative类。基本上,它会根据数字是负数还是绿色将.gains元素修饰为红色或绿色。正)。

这是因为AJAX调用是异步的。 当您调用decorateGains()函数时,请求尚未完成(因此新内容尚未添加到DOM)。 在设置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