仍然没有添加到 DOM 中,但如果插入了警报/确认,则会获取标签 ID

Still not added to the DOM but if and alert/confirm inserted get the tag ID

本文关键字:确认 ID 标签 获取 如果 添加 DOM 插入      更新时间:2023-09-26

我有这段jquery/javascript,我不明白为什么会发生这种情况以及我应该如何修复它。 带有 id="group_"+num 的标签加载了 ajax,所以它似乎还没有被添加到 DOM 中,有趣的是如果我在中间放一个警报,函数就可以工作,没有那个警报什么都没有发生,¿任何人都可以解释那里有什么警报以及我应该怎么做才能在 DOM 中获取该 id,以便 jquery 可以将长度计算为 1?当然,如果我得到任何其他未加载 ajax 的 id,则可以工作。

$(document).ready(function(){
    $(function() {
    var hash = window.location.hash;
    var num = hash.replace("#subcat_group_","");
    $('[id*="subcat_group_"]').hide();
            // here the "id" loaded with ajax seems still not loaded.
    var len = $("#group_"+num).length;
           //Here variable "len" still 0 
           /***** with this alert works , just an alert anything inside
           alert(num);
           with this alert works *****/ 
          /*******if i use "len" here still 0 even if alert is before *******/
           if( $("#group_"+num).length === 1){

          /******if i get again for id lenght with alert before , then is 1 ******/              
        if( $("#group_"+num).length === 1){
        var group_name = $("#group_"+num).attr("title");
        swapContentV1(num,group_name);
    }
    $("#subcat_group_"+num).show();
    });
});

谢谢。

警报会强制脚本等待...以便您的响应并完成 Ajax 调用。没有警觉,你看起来"太早了"——那时阿贾克斯还没有完成。

你应该把你的代码放到成功函数中,正如shoogle在他的评论中建议的那样。