【问题标题】:Waiting for ajax response append and load content before firing function在触发函数之前等待 ajax 响应追加和加载内容
【发布时间】:2013-09-08 15:43:18
【问题描述】:

您好,我有一个项目,我使用 ajax 帖子从服务器获取帖子,我检测附加帖子中的图像并使用函数根据它们的比例调整它们的大小。

问题是当我添加新帖子并尝试触发该功能时,它会将图像检测为大小(高度和宽度)0,导致图像尚未加载。我搜索了,但找不到任何答案,有一种方法可以检测 ajax 响应中的所有图像(其中包含其他元素)是否已使用 .onload 或其他替代方法加载?

【问题讨论】:

    标签: ajax image resize load append


    【解决方案1】:
                                       **Update**
    

    我想通了:

    检查 ajax 响应中的 img 元素长度:

    $("#yourelement").append(html);
    var $dialog = $(html);
    imglength = $dialog.find("img").length;
    

    在每个加载的 img 上添加一个 count++,并检查它是否等于 img 长度:

    n_images = 0;
    $("#yourelement img").on('load', function(){ // check for every new image loaded in # 
    n_images++;
    
    if (n_images == imglength) {
    //alert(imglength); // I used to verify if it works
    yourfunction(); // will fire when all new images have been appended and loaded
    }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多