简体   繁体   中英

Callback function executed first

I made the following code:

function popup(content,callback){
// create the overlay
var $overlay = $('<div />').appendTo('body');
    $overlay.attr('class','overlay');
// create a popup
var $popup = $('<div />').appendTo('body');
    $popup.attr('class','popup');
// add the image
if(typeof content.imageUrl !== 'undefined'){
    var $popup_image = $('<img />').appendTo($popup);
        $popup_image.attr('src',content.imageUrl);
        $popup_image.attr('class','popup_img');
};
// create a popup title
var $popup_title = $('<h1 />').appendTo($popup);
    $popup_title.attr('class','popup_h1');
    $popup_title.html(content.title);
// create a popup body
var $popup_body = $('<p />').appendTo($popup);
    $popup_body.attr('class','popup_p');
    $popup_body.html(content.text);
// create a popup close
var $popup_close = $('<span />').appendTo($popup);
    $popup_close.attr('class','close');
    $popup_close.html('x');
// create the fadeIn/fadeOut speed
if(typeof content.speed !== undefined){
    var popup_fadespeed = content.speed;
} else {
    var popup_fadespeed = 'slow';
};
    // bind the close function to $popup_close
    $popup_close.bind('click',function(){
        $popup.fadeOut(popup_fadespeed);
        $overlay.fadeOut(popup_fadespeed);
    });
    // bind the close function to $overlay
    $overlay.bind('click',function(){
        $popup.fadeOut(popup_fadespeed);
        $overlay.fadeOut(popup_fadespeed);
    });
    // show the overlay
    $overlay.fadeIn(popup_fadespeed);
    // show the popup
    $popup.fadeIn(popup_fadespeed);

    if(callback && typeof(callback) === "function"){
        return callback();
    } else {
        return;
    }}

It creates a popup in my window, and everything workes find, exept for the callback.

when I do something like this:

$("#test").click(
function(){popup(
{
    title : 'title',
    text : 'text',
    imageUrl : 'http://localhost/frontend/media/images/logo.png',
    speed : 'slow'
},
function(){$('body').css('background','red');}
)});

Now the body background changes before the popup shows. When I test it with an alert, the alert also shows up before the popup (so it looks like the callback function is executed first).

Can someone help me out with this? Or locate the mistake I made in the code?

Thanks in advance

Change the last to this:

if(callback && typeof(callback) === "function"){
   $popup_image.load(callback);
    } else {
        return;
    }}

.load is a wrap of dom element img 's onload , which if you put some function into it, it'll executes after image is loaded. jquey.load

Add jsfiddle to show it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM