开发者

jquery synchronous execute

Very Sorry for my english,i have a problem.

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

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.

Questio开发者_高级运维n 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);

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);
}

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

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 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.

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


You don't want it to be synchronous, you want to be able to run your function at the right asynchronous point.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜