jQuery同步执行 [英] jquery synchronous execute

查看:418
本文介绍了jQuery同步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我的英语不好,我有问题.

Very Sorry for my english,i have a problem.

$("#MainPicture").attr("src", url);
CenterImg();

需要在第1行代码完成之后执行第2行代码.它是异步的,我想通过同步来执行代码.谢谢大家.

needs to be execute line 2 code after line 1 code finished . it is asynchronous and i want the code excute by synchronous . Thanks All.

问题详细信息; 加载图片后,我想在中央屏幕上移动$(#MainPicture").

Question Details; i want to move $("#MainPicture") in the center screen when picture loaded.like this.

$("#MainPicture").attr("src", url);
// new picture width,not old picture width
var PictureWidth=$("#MainPicture").width();
var ScreenWidth=$(window).width();
var ResultWidth=(ScreenWidth-PictureWidth)/2;
$("#MainPicture").css("left",ResultWidth);

实际上,在第2行代码中,我总是得到旧的图片宽度.

in fact,in line 2 code,i alway get old picture width.

推荐答案

$("#MainPicture").attr("src", url).one('load', CenterImg );

function CenterImg() {
    var PictureWidth = $("#MainPicture").width();
    var ScreenWidth = $(window).width();
    var ResultWidth = (ScreenWidth - PictureWidth) / 2;
    $("#MainPicture").css("left", ResultWidth);
}

这会使用 one() [docs] 方法,它简单地绑定处理程序,并在第一次执行后将其解除绑定.

This adds a load handler using the one()[docs] method, which simply binds the handler, and unbinds it after the first time it executes.

在这种情况下,处理程序是您的CenterImg()函数,因此它将在图像加载完成后被调用.

The handler in this case is your CenterImg() function, so it will be invoked when the image is finished loading.

如果有可能缓存了图像,但您仍然希望调用该函数,则可以执行以下操作:

If there's a chance that the image is cached, and you still want the function to be invoked, you can do this:

$("#MainPicture").attr("src", url)
                 .one('load', CenterImg )
                 .filter(function() { return this.complete; })
                 .load();

function CenterImg() {
    var PictureWidth = $("#MainPicture").width();
    var ScreenWidth = $(window).width();
    var ResultWidth = (ScreenWidth - PictureWidth) / 2;
    $("#MainPicture").css("left", ResultWidth);
}

这样,如果图像已经加载,则this.complete将返回true,并且 filter() [docs] 方法将返回带有该图像的jQuery对象,以便您可以手动调用.load()处理程序.

This way if the image is already loaded, this.complete will return true, and the filter()[docs] method will return a jQuery object with that image so you can manually invoke your .load() handler.

如果图像的 not 加载尚未完成,则.filter()将返回0元素,而手册load()将无效.

If the image has not yet finished loading, the .filter() will return 0 elements, and the manual load() will have no effect.

这篇关于jQuery同步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆