如何使用jQuery.ajax动态修改添加的html

How can I modify dynamically added html with jQuery.ajax?

本文关键字:添加 html 修改 动态 何使用 jQuery ajax      更新时间:2024-05-06

我在jQuery中有一个ajax调用,它在我的站点中返回并插入一些HTML。在同一个调用中,在成功回调中,我想对返回的html"做一些事情"。

一些代码(简化):

$.ajax({
    url: "some_url.php",
    type: 'POST',
    dataType: 'json',
    data: some_data,
    success: function(response){
        myAsyncAjaxInsertHtmlFunction(response); // 1. This function is an ajaxcall which inserts HTML dynamically
        $(newlyAddedSelector + ' input').each(function(){ // 2. Here I want to iterate over those dynamically added html elements
            doStuffWithNewlyAddedHtml(this.value);
        });
    }
});

问题是,当代码执行到达第2点时,动态添加的html还没有加载。我知道async:false存在,但这不是我想走的路线。

你应该如何处理这种情况,我可以想象这种情况很常见?

您可以使用fct().done()等待ajax执行完毕,然后再转到第二个进程

function ajax1() {
    return $.ajax({
        url: "someUrl",
        ...
    });
}

ajax1().done(function(){
        // the code here will be executed when ajax requests resolve.
    });

编辑的

 var insered = false;
 $.ajax({
    url: "some_url.php",
    type: 'POST',
    dataType: 'json',
    data: some_data,
    success: function(response){
        myInsertHtmlFunction(response); // 1. This function inserts HTML dynamically
        insered = true;
        },
    complete: function(){
        if( insered == true ) {
              $(newlyAddedSelector + ' input').each(function(){ // 2. Here I want to iterate over those dynamically added html elements
                 doStuffWithNewlyAddedHtml(this.value);
             });
        }
    }
});

你可以插入你的html成功地做你的最后的东西在完整的方法。

除非您的myInsertHtmlFunction函数执行async,否则您的代码应该可以工作,因为添加&删除HTML元素总是同步的。

但是,如果您的应用程序逻辑也修改HTML,这取决于一些新添加的元素的加载状态,例如,如果新添加的图像完成加载,则添加div,那么您的代码将失败。

这完全取决于myInsertHtmlFunction函数。