jquery
2010-09-21 40 views 2 likes 
2

我的想法起初是这是一个语法问题,但我没有看到任何语法问题。我已经添加调试代码,这给了奇怪的结果,x登录之前jQuery('#notification')执行setTimeout后元素列表后的Javascript错误“丢失”

document.triggerNotification = function (type, message) { 
    jQuery(document.body).append("<div class='push-notification push-"+type+"' id='notification'>"+message+"</div>"); 

    setTimeout(jQuery('#notification').fadeOut(1200, function() { 
     console.log(jQuery('#notification')); 
     jQuery('#notification').remove(); 
     console.log(jQuery('#notification')); 
    }), 3000); 
    console.log('x'); 
} 

萤火虫提供了以下的输出:

x 
[div#notification.push-notification] 
[] 
missing ] after element list - [Break on this error] [object Object] 

一切都成功执行,但它仍然抛出一个错误。

回答

10

setTimeout需要一个函数作为它的第一个参数。你给它一个jQuery对象的集合。请尝试以下操作:

document.triggerNotification = function (type, message) { 
    jQuery(document.body).append("<div class='push-notification push-"+type+"' id='notification'>"+message+"</div>"); 

    setTimeout(function() { jQuery('#notification').fadeOut(1200, function() { 
     console.log(jQuery('#notification')); 
     jQuery('#notification').remove(); 
     console.log(jQuery('#notification')); 
    })}, 3000); 
    console.log('x'); 
} 

注意,已缠你jQuery('#notification').fadeOut()调用匿名函数。用你当前的代码,我期望fadeOut立即执行,而不是在指定的3秒后执行。

+1

不要忘记删除'console.log()' – Sam 2010-09-21 14:51:45

相关问题