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

Javascript 在加载了AJAX的DOM元素上运行jQuery脚本,javascript,jquery,ajax,dom,Javascript,Jquery,Ajax,Dom,我知道当通过AJAX加载DOM内容时,jQuery不会运行。但我不明白为什么。我的理解是,在jQuery启动时DOM元素不存在,因此它找不到正确的ID或类 但是我有一种情况,只有在所有内容都通过AJAX加载之后才调用jQuery。但它仍然不起作用 这是我的密码。我试图在AJAX完成后运行函数decoregains() loadData('7-days'); // Runs the default AJAX for 7 days function loadData(type){ var x

我知道当通过AJAX加载DOM内容时,jQuery不会运行。但我不明白为什么。我的理解是,在jQuery启动时DOM元素不存在,因此它找不到正确的ID或类

但是我有一种情况,只有在所有内容都通过AJAX加载之后才调用jQuery。但它仍然不起作用

这是我的密码。我试图在AJAX完成后运行函数
decoregains()

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()
函数的末尾包含了对函数
decoregains()
的调用

decoregains()
函数确实在运行,因为我可以看到我的控制台消息。然而,它并没有完成它应该完成的任务

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");
        }
    });
}
函数decoregains(){
console.log('here');
$(“.gains”).each(函数(){
var num=+($(this.text());
如果(数值>0){
console.log('here');
$(此).addClass(“正”);
}
if(num<0){
console.log('here');
$(此).addClass(“负”);
}
});
}

(脚本搜索类为
.gains
的所有元素,并根据元素的内容添加一个新类
正数
负数
。本质上,它将
.gains
元素装饰为红色或绿色,具体取决于数字是负数还是正数)这是因为AJAX调用是异步的。调用
decoregains()
函数时,请求尚未完成(因此新内容未附加到DOM)。设置
innerHTML
后,需要将对函数的调用放入
onreadystatechange
处理程序中:

loadData('7天');//运行默认AJAX 7天
函数loadData(类型){
var-xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=新的XMLHttpRequest();
}否则{
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById(“主表”).innerHTML=xmlhttp.responseText;

decoregains();//您的问题是,ajax是一个asunchron。因此,
decoregains();
在响应到达之前运行。谢谢。这是一个很好的解释,感谢代码示例。我知道这是一个大致相同的问题:)@Francesca一点问题也没有,很高兴提供帮助。