2015-06-20 63 views
0

我做了如下代碼:回調函數執行第一

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

它在我的窗口創建一個彈出,一切workes發現,exept回調。

,當我做這樣的事情:

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

現在擺在彈出的顯示人體背景變化。當我用警報測試它時,警報也出現在彈出框之前(所以看起來像回調函數首先被執行)。

有人可以幫我解決這個問題嗎?或者找到我在代碼中犯的錯誤?

在此先感謝

+0

我的猜測與你添加一個圖像到DOM和異步加載的圖像有關,所以你最終在內容真正可見之前運行你的代碼。大概你可以找到[圖片加載插件](https://github.com/desandro/imagesloaded) –

+0

'return callback()'調用函數,然後返回它的返回值。沒有什麼可以讓它等到淡出效果之後,這將會異步發生。你嘗試過'$ popup.fadeIn(popup_fadespeed,callback);'? – nnnnnn

+0

@nnnnnn謝謝,它的作品! – samleurs

回答

0

更改最後這一點:

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

.load是的DOM元素imgonload,如果你把一些功能在它之上的包裹物,之後它會執行圖像被加載。 jquey.load

添加jsfiddle以顯示它的工作原理。

+0

當我添加那段代碼時,沒有任何東西顯示出來(如警報)。當我設置$ popup.load(callback())(和回調函數後)時,回調會在加載彈出窗口之前觸發。 – samleurs

+0

糟糕,我搞砸了'$ popup'和'$ popup_image',編輯過,再試一次? – fuyushimoya

+0

也不起作用。但我現在得到了解決方案(請參閱我的第一篇文章中的評論) – samleurs

相關問題