有一个小问题,我似乎不能弄清楚。
我有一个关于CMS的博客文章,我正在建设,有一些内容保存到一个div与它自己的唯一ID。当用户单击编辑按钮时,将显示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成功返回,但它不做任何事情。
任何想法?
如果您试图为已经添加到页面的图像绑定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
});
}