javascript - 尽管由 ajax 加载,但 DOM 元素只是偶尔创建

标签 javascript jquery css ajax dom

这是一个非常具体的问题,让我特别困惑。元素简而言之:我在一个咨询网站上工作,该网站从 API 获取数据并加载了 AJAX。我现在正在尝试让旧的、存档的聊天记录在菜单中单击时预加载并使用 css 显示。

这就是问题所在:它有效……但只有大约三分之一或在重新加载页面后。我不明白那是怎么回事,它应该起作用还是不起作用。 我检查过,数据总是被加载(它必须是因为当前聊天首先打开并且总是有效) 那怎么可能呢?

$.ajax({
    type: 'POST',
    url: '/vsbt/counselling/archive/',
    data: {},
}).done(function(data) {
    console.log('ajax /vsbt/counselling/archive/');
    console.log(data);

    //menu is created
    $('#counselling_status').append('<ul class="archivedCounsellings"></ul>');
    $('.archivedCounsellings').append('<h2>Archivierte Chats</h2>')

    for (var i = 0; i < data.length; i++) {
        //menu items are added
        var that = data[i].messages[0].title;
        $('.archivedCounsellings').append('<li class="' + that + '"><a>' + that + '</a></li>')
        $('#vbst_communication_container').prepend($('<div class="counselling inactive ' + that + '" />')
            .append($('<h2>' + that + '<h2>')));

        //the messages are added with to classes for styling
        data[i].messages.forEach(function(message) {
            $("div." + that)
                .append($('<div />')
                    .addClass(message.type)
                    .append($('<p />')
                        .text(message.message)))
        });
        //this doesn't work either, you can maybe tell me why, but that's not the issue
        $('.counselling').data("status", [i]);
    }

    $(".archivedCounsellings").append('<li class="aktuell"><a><br>Zur aktuellen Beratung</a></li>');

    //click event to toggle the displayed counseling
    $('.archivedCounsellings li').click(function() {
        $('.counselling').addClass('inactive');
        $('div .' + $(this).attr('class')).removeClass('inactive');

        //workaround which works, but isn't really acceptable
        // no load workaround
        // if($('.openCounselling').siblings().length == 0){
        //     window.location.reload();
        // }

        // $('.statusDisplay').text($('#job_status_' + $(this).attr('class')).data("status"));
        // console.log($('div .' + $(this).attr('data-status')));
    });

附言。我知道“咨询”中的拼写错误
聚苯硫醚。如果您发现一个明显导致失败的错误,那可能是在复制时发生的,因为请记住,它有时确实有效。

最佳答案

好吧,如果有人遇到过这个问题:我刚刚对 AJAX 做了更深入的解释,基本上 AJAX 或多或少同时发出了所有请求。 done 函数中发生的任何事情都会在那之后发生,因此数据请求成功。 我所做的是在不同的函数中为所述元素启动容器。所以偶尔那个有点慢,没有地方可以将我的元素附加到 --> 没有错误,只是什么也没发生。 不太可能有人会看到这个,因为它非常具体,但也许这会对某人有所帮助,至少我现在知道得更多

关于javascript - 尽管由 ajax 加载,但 DOM 元素只是偶尔创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40736448/

相关文章:

javascript - AJAX 成功不适用于 IE 和 Firefox

javascript - 为什么 jQuery .attr() 在 IE9 中不起作用?

javascript - 为在线表格制作打印布局

javascript - 在导航菜单中突出显示事件选项卡

javascript - 何时将样式表添加到 document.styleSheets

javascript - 具有多行的 jQuery 光滑 slider 不起作用

javascript - 需要用图像替换 innerText 以表示圆点和十字

javascript - 为什么我不应该直接访问实例属性进行写操作?

javascript - 选择具有特定文本的按钮仅在单击事件时激活

javascript - 悬停在 iframe 上时,如何在 iframe 外部的元素上触发类?