我创建了一个片段,它检查一个 div 内的所有图像并根据它们的大小添加一个类。
我目前已经在文档中准备好了这个,当页面加载时我工作得很好。
但是,我正在制作一个 CMS,您可以在其中编辑页面本身的文本,然后通过 ajax 进行更新。
调用响应通常如下所示:
success: function (response) {
if (response.databaseSuccess) {
$("#container #" +response.postid).load("#container #" +response.postContentID);
$targetForm.find(".saveupdatebutton").qtip("hide");
}
}
在此之后,通过 .load() 函数加载的 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
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');
});
最佳答案
根据您使用的 jQuery 版本,您可以像这样将 .on
更改为 .live
:
box.find("img.buildimage").live('load', function () {
如果这不起作用,那么您可以尝试以下操作。那么你必须按照下面的“正确”方式进行操作:
首先外部化图像大小调整的函数:
$(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
var box = $(".blogtest");
box.find("img.buildimage").on('load', imageOnload)
.filter(function () {
//if the image is already loaded manually trigger the event
return this.complete;
})
.trigger('load');
});
function imageOnload(evt){
var img = $(evt.currentTarget),
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");
}
}
然后,您可以在成功回调中添加此语句:
$("#container #" +response.postid).on("load", imageOnload);
关于javascript - 在 ajax 成功回调中运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528203/