将元素附加到 - 将 while 与动态添加的元素一起使用

append elements until - using while with dynamic added elements

本文关键字:元素 添加 动态 一起 while      更新时间:2023-09-26

我有添加到div 容器div 的函数

 $.ajax(
    {
        type: "GET",
        url: "/LoadedData",
        data: { "pageNumber": pageNumber },
        success: function (result) {
            $('.Container').append(result);
        }
    }

我想执行该函数,直到这个div 容器包含div 与 是 xxx

我尝试使用 while 循环执行此操作,但看起来像我这样做时:

while($('.Container div').is('#xxx'))
{}

函数看不到附加到容器的新div:/

将代码放在callback:中递归调用的函数中,如果result与选择器不匹配。

它将继续运行,直到选择器匹配。

var container = $('.Container');  // cached the .Container element
function add_to_container() {
   $.ajax(
    {
        type: "GET",
        url: "/LoadedData",
        data: { "pageNumber": pageNumber },
        success: function (result) {
            container.append(result);
            if( !$(result).is("#xxx") ) {  // if the result was not the one...
                add_to_container();       // ...recursively call the function
            }
        }
    }
}

Jquery 具有遍历 dom 元素的 each 函数。

$('.Container div').each(function(){});