为什么 AJAX 之后的 DOM 不完整

Why is the DOM incomplete after AJAX

我有一个 AJAX 函数,它使用 on('click')... 委托函数填充页面并创建 2 个或更多 flex 容器,每个容器都有自己的唯一 ID。 id 和 class 显示在每个 flex div 块中。代码概要如下所示:

$('li.dicap_menu_action a').on("click",function(){
  var dicap_action =  $(this).attr("href");
  $.ajax({
    //call to php function that defines the blocks
  });
  return false; //prevent the browser from following the link
});

这工作正常,输出如下所示

接下来我想根据块的id值向每个块添加内容,然后问题就开始了。作为概念证明,我创建了一个名为 populate_snapshot 的函数,并将函数调用添加到 AJAX 函数下方的代码中:

$('li.dicap_menu_action a').on("click",function(){
    var dicap_action =  $(this).attr("href");
    $.ajax({
        //call to php function that defines the blocks
    });
    populate_snapshot();
    return false; //prevent the browser from following the link
});

使其直接在AJAX函数之后执行,替换每个块中的内容。 populate_snapshot 函数看起来像这样

function populate_snapshot(){
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

但是,控制台日志没有找到 flex 容器,并且在 运行s 时输出没有改变。

如果我将 alert() 添加到 populate_snapshot 中,如图所示,那么在我关闭弹出窗口后该函数可以正常工作:

function populate_snapshot(){
    alert('Test');
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

控制台日志显示 2 个 flex 容器,输出变为

好像 DOM 需要先刷新 populate_snapshot 函数才能 运行。有什么方法可以做到这一点,还是我缺少一些更基本的东西。这是一个事件冒泡问题吗?还有其他方法可以委托 populate_snapshot 函数,以便它在 AJAX 调用完成后自动 运行s 吗?

我考虑过在 AJAX 之后使用 ajaxComplete() 来触发 populate_snapshot,但这行不通,因为我的 populate_snapshot 稍后将使用另一个 AJAX 函数并且这将导致无限循环。

如有任何帮助,我们将不胜感激。

感谢@Andreas 的建议 - 这个答案完全归功于他。

以下是我如何使用此建议来解决我的问题。代码的 AJAX 部分更改如下(注意 .then() 函数):

$('li.dicap_menu_action a').on("click",function(){
    var dicap_action =  $(this).attr("href");
    var aj = $.ajax({
        //call to php function that defines the blocks
    });
    aj.then(function(){
      populate_snapshot();
    })
    return false; //prevent the browser from following the link
});

populate_snapshot函数是:

function populate_snapshot(){
    var $flx = $('div.dicap-flex-2');
    console.log($flx);
    $flx.each(function() {
        $(this).html('This block was found');
    });
}

概念验证输出符合预期

再次感谢@Andreas 和所有问题。