2013-07-26 96 views
0

我正在研究一個名爲「popup」的插件($(".messageBox").popup())。jQuery插件無法正常工作

這裏是我的代碼部分:

$(this).fadeIn(settings.fadeDuration); 
    console.log($(this).attr("class")); 

    console.log(settings.timeOut); 
    setTimeout(function(){ 
     console.log($(this).attr("class")); 
     $(this).fadeOut(settings.fadeDuration); 
}, settings.timeOut); 

那是在popup.min.js的代碼,現在下面是index.html代碼:

$(function(){ 
    $(".messageBox").popup(); 
}); 

我的彈出窗口,並正確淡入,但它不會在1000ms之後淡出......我該怎麼辦?我打開了控制檯,但沒有顯示錯誤。

+0

什麼是'setting.timeOut'寫入控制檯時? – War10ck

回答

2

因爲this參考是錯誤的setTimeout回調方法裏面

您可以使用一個閉包變量保持參考

$(this).fadeIn(settings.fadeDuration); 
console.log($(this).attr("class")); 

console.log(settings.timeOut); 
var el = this; 
setTimeout(function(){ 
    console.log($(el).attr("class")); 
    $(el).fadeOut(settings.fadeDuration); 
}, settings.timeOut); 

或使用$.proxy()到自定義上下文傳遞給回調

$(this).fadeIn(settings.fadeDuration); 
console.log($(this).attr("class")); 

console.log(settings.timeOut); 
setTimeout($.proxy(function(){ 
    console.log($(this).attr("class")); 
    $(this).fadeOut(settings.fadeDuration); 
}, this), settings.timeOut); 
+0

謝謝@Arun,這幫了我很多! – Victor