回调加载函数jQuery
问题描述:
我希望能够在创建元素(图像元素)时执行函数的回调。代码工作,通过这个代码加载一个新的形象元素:回调加载函数jQuery
$('<img />').load(function()
{
var img = this;
$('.block-wrap img').fadeOut('slow', function()
{
$(this).replaceWith(img);
});
}).attr('src', loadurl);
但我希望能够继续当图像已经加载和更换。这是我需要它的工作:
$('<img />').load(function()
{
var img = this;
$('.block-wrap img').fadeOut('slow', function()
{
$(this).replaceWith(img);
});
}).attr('src', loadurl);
$('.block-wrap input.imageheight').val($('.block-wrap img').height());
$('.block-wrap input.imagewidth').val($('.block-wrap img').width());
它返回第一个图像高度(不是已被替换这是一个正在加载的旋转图像的图像),所以我需要它能够检索图像高度以及当它完全加载到DOM时的宽度。太糟糕了.replaceWith()
没有回调方法,但我不能在上使用回调函数,因为它不起作用,因为它是通过函数传递的函数。
答
我不是100%在这个,但你不能添加一个加载事件到replaceWith结束?即:
$(this).replaceWith(img).load(function(){ $('.block-wrap input.imageheight').val($('.block-wrap img').height()); $('.block-wrap input.imagewidth').val($('.block-wrap img').width()); });
答
它返回错误的图像尺寸,因为$('.block-wrap img').height()
和$('.block-wrap img').width()
被称为之前结束。
您可以在load
回调内(.replaceWith
之后)放入那两行,以便它们引用正确的图像。
$('<img />').load(function()
{
var img = this;
$('.block-wrap img').fadeOut('slow', function()
{
$(this).replaceWith(img);
$('.block-wrap input.imageheight').val($('.block-wrap img').height());
$('.block-wrap input.imagewidth').val($('.block-wrap img').width());
});
}).attr('src', loadurl);
嗯。它似乎是合理的,它总是为每个值返回“0”,所以我用100ms的setTimeout()将它们包装起来,它返回了图像尺寸。仍然不确定是否有比这更好的解决方案。 – MacMac 2011-03-24 16:39:35