jQuery 加载函数的回调
我希望能够在创建元素(图像元素)时回调 .load()
函数。该代码的工作原理是通过以下代码加载新的图像元素:
$('<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()
没有回调方法,但我无法在 .load()
上使用回调函数,因为它是一个函数,因此无法工作已通过 .load()
函数传递。
I want to be able to do the callback of the .load()
function when an element has been created - an image element. The code works by loading a new image element by this code:
$('<img />').load(function()
{
var img = this;
$('.block-wrap img').fadeOut('slow', function()
{
$(this).replaceWith(img);
});
}).attr('src', loadurl);
But I want to be able to continue when the image has been loaded and replaced. This is how I need it to work:
$('<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());
It returns the first image height (not the image that has been replaced which is a loading spinner image), so I need it to be able to retrieve the image height and width when it has fully loaded into the DOM. Too bad .replaceWith()
does not have a callback method, but I cannot use a callback function on the .load()
since it will not work due to it's a function that has been passed through the .load()
function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它返回错误的图像尺寸,因为
$('.block-wrap img').height()
和$('.block-wrap img').width()
在.load()
完成之前被调用。您可以将这两行放在
load
回调中(在.replaceWith
之后),以便它们引用正确的图像。It's returning the wrong image dimensions, because
$('.block-wrap img').height()
and$('.block-wrap img').width()
are being called before.load()
finishes.You can put those two lines inside the
load
callback (after the.replaceWith
), so that they refer to the correct image.我不是 100% 同意这一点,但是你不能在 ReplaceWith 的末尾添加一个加载事件吗? IE:
I'm not 100% on this but could you not add a load event to the end of replaceWith? I.E: