在执行setTimeout之后元素列表之后的Javascript错误"缺失"

Web*_*net 2 jquery

我一开始的想法是这是一个语法问题,但我没有看到任何语法问题.我已经添加了调试代码并且给出了奇怪的结果,x之前已经记录过jQuery('#notification')

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');
}
Run Code Online (Sandbox Code Playgroud)

Firebug提供以下输出:

x
[div#notification.push-notification]
[]
missing ] after element list - [Break on this error] [object Object]
Run Code Online (Sandbox Code Playgroud)

一切都成功执行但它仍然抛出错误.

Rya*_*nal 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');
}
Run Code Online (Sandbox Code Playgroud)

请注意已绕过您的jQuery('#notification').fadeOut()呼叫的匿名功能.使用当前代码,我希望fadeOut立即执行,而不是在指定的3秒后执行.