我做了如下代碼:回調函數執行第一
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');}
)});
現在擺在彈出的顯示人體背景變化。當我用警報測試它時,警報也出現在彈出框之前(所以看起來像回調函數首先被執行)。
有人可以幫我解決這個問題嗎?或者找到我在代碼中犯的錯誤?
在此先感謝
我的猜測與你添加一個圖像到DOM和異步加載的圖像有關,所以你最終在內容真正可見之前運行你的代碼。大概你可以找到[圖片加載插件](https://github.com/desandro/imagesloaded) –
'return callback()'調用函數,然後返回它的返回值。沒有什麼可以讓它等到淡出效果之後,這將會異步發生。你嘗試過'$ popup.fadeIn(popup_fadespeed,callback);'? – nnnnnn
@nnnnnn謝謝,它的作品! – samleurs