javascript - 对通过 .load() 函数加载的内容进行检查

标签 javascript php jquery html ajax

有一个我似乎无法弄清楚的棘手问题。

我有一篇关于我正在构建的 CMS 的博客文章,并且有一些内容保存到具有自己唯一 ID 的 div 中。当用户单击编辑按钮时,将显示一个 CKeditor(包含与 div 相同的文本)。我还显示一个保存按钮,单击该按钮后,将通过 AJAX 调用处理 PHP 脚本。

数据库更新成功后,我在 AJAX 调用中使用它:

if (response.databaseSuccess) {
  $("#container #" +response.postid).load("#container #" +response.postContentID);
}

这工作得很好,并将更新的内容加载到 div 中。

现在的问题...

在页面加载时我使用这个:

$(document).ready(function () {
    // check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
    function resize() {
    var box = $(".blogtest");
    box.find("img.buildimage").on('load', function () {
        var img = $(this),
            width = img.width();
        if (width >= 650) {
            img.addClass("buildimage-large");
        } else if (width < 500 && width > 101) {
            img.addClass("buildimage-small");
        }
        // if image is less than X, its most likely a smiley
        else if (width < 100) {
            img.addClass("buildimage-smiley");
        }
        }).filter(function () {
            //if the image is already loaded manually trigger the event
            return this.complete;
        }).trigger('load');
    }
    resize();
});

这有效,并检查图像的宽度并采取相应的措施。页面完全加载后,图像会正确地获得新的类,从而改变它们的宽度。

问题是我无法让这个函数处理保存的数据。因此,当我单击“保存”并通过 .load() 加载内容时,不会检查新图像。

我尝试将上述函数添加到 AJAX 成功返回中,但它没有执行任何操作。

有什么想法吗?

最佳答案

如果您尝试 Hook 已添加到页面的图像的 onload 事件,则很容易错过 onload 事件,特别是如果该图像已经在浏览器缓存中(因此会快速加载),因为在您有机会附加事件处理程序之前,onload 事件可能已经触发。通常的解决方法是执行类似以下操作,在附加 onload 处理程序之前检查它是否已加载:

box.find("img.buildimage").each(function() {
    if (this.complete) {
        // image already loaded so just process it here
    } else {
        // image not yet loaded so attach an onload handler
        $(this).on("load", function() {
            // now the image is loaded so process it here
        });
    } 
});
<小时/>

我不确定您到底使用什么代码来动态加载新内容。如果您使用 Ajax 执行此操作,则需要确保在将内容添加到页面(您正在使用的任何加载操作的成功或完成处理程序)之前不会触发上述代码。

因此,如果您要在此处加载新内容:

if (response.databaseSuccess) {
  $("#container #" +response.postid).load("#container #" +response.postContentID);
}

然后,您可以在 .load() 函数上使用完成处理程序回调来触发上述代码:

if (response.databaseSuccess) {
  $("#container #" +response.postid).load("#container #" +response.postContentID, function() {
      // code here that looks at the dynamically loaded content
  });
}

关于javascript - 对通过 .load() 函数加载的内容进行检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316554/

相关文章:

javascript - 基于标题连接数组列

php - while循环使用复选框php mysql仅插入最后一行

javascript - jQuery PHP 表单提交错误

php - 搜索结果后如何更新库存数量?

javascript - 在 if 条件下将变量与空 jquery 对象进行比较

javascript - 如何在 DOM 中搜索下一个元素?

javascript - 没有关闭按钮的jquery弹出窗口

javascript - 我可以向 html 元素添加自定义属性吗?

php - 在线时 CodeIgniter 验证码图像不起作用

javascript - 使用单击事件超链接表行