对通过.load()函数加载的内容运行检查
Running a check on content loaded in via a .load() function
有一个小问题,我似乎不能弄清楚。
我有一个关于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
});
}
相关文章:
- PhantomJS - 检查javascript函数是否正在运行的任何方法
- 如何检查函数是否将运行或可用
- 检查在使用节点运行程序时是否给出ARGV
- 检查grunt是否在详细模式下运行
- 在浏览器检查表单之前运行javascript onsubmit
- JavaScript游戏引擎——编辑器中的代码运行:)检查器中的错误
- 什么更快?运行空函数或检查函数是否未定义
- 在运行Javascript/jQuery中的函数之前,检查元素是否存在是否更具性能
- 从Javascript运行PHP文件来检查在线用户:表示未登录的用户是
- 每次用户单击按钮时运行if语句检查器
- 在不重新运行jquery验证的情况下检查表单是否有效
- 检查运行到CORS的图像是否存在
- 代码运行时的类型检查
- 通过ajax运行php页面时,请检查javascript中单击了哪个按钮
- 流星 - 检查您是否运行了 2 个版本的 React
- 当我通过 SHA1 运行字符串时的值与使用 .charCodeAt() 检查它时的值不同
- JavaScript 函数可以检查它是否在 Web Worker 线程上运行吗?
- Jasmine 测试在测试运行中、Firefox/Chrome 之间以及检查器开/关时的结果不一致
- 角度始终运行检查
- 对通过.load()函数加载的内容运行检查