2013-04-30 56 views
-3
$('#myElement').datepicker(
    { 
     dateFormat: 'yy-mm-dd', 
     onClose: function() { 
      $(this).DoStuff; 
      console.log('close'); 
     }, 
     beforeShowDay: nationalDays, 
     minDate: new Date() 
    } 
); 

function DoStuff() { 
    console.log('DoStuff'); 
} 

我試圖在datepicker關閉時調用DoStuff。我的控制檯顯示「關閉」,但不顯示「DoStuff」。我究竟做錯了什麼?jQuery UI onClose調用函數

回答

3

$(this).DoStuff不會調用$(this)對象的DoStuff功能,但嘗試訪問$(this)對象的DoStuff財產。在你的情況下,它什麼都不會做:它將被解析爲未定義的,並且訪問屬性很可能沒有副作用,所以什麼都不會發生。

因爲你的問題是非常基本的我敢肯定有一個誤解,這裏是你如何調用DoStuff功能:

DoStuff(); 

所以這個就足夠了:

$('#myElement').datepicker(
    { 
     dateFormat: 'yy-mm-dd', 
     onClose: function() { 
      DoStuff(); 
      console.log('close'); 
     }, 
     beforeShowDay: nationalDays, 
     minDate: new Date() 
    } 
); 

編輯

其實,如果你要撥打的jQuery對象上的功能(雖然我不知道你真的想這樣做),你可以擴展的對象是這樣的:

jQuery.fn.DoStuff = function() { 
    console.log('DoStuff'); 
} 

然後你就可以致電$(this).DoStuff()。這樣this將是你的函數內部jQuery對象,檢查:

jQuery.fn.DoStuff = function() { 
    console.log(this); 
    console.log(this[0]); //the first (and in this case the only) element selected by the selector 
} 

$('#myElement').DoStuff(); 
1

那麼你不叫它

$(this).DoStuff; <-- missing the() 

而且DoStuff沒有連接到$(this)所以它不會工作,我期望看到擴展,你的代碼沒有。

這大概應該是

DoStuff(); 

DoStuff.call($(this)); 
1

$(this).DoStuff()意味着DoStuff()是對象,這似乎並沒有這樣的情況的一個成員函數。

您應該改爲doStuff($(this));,並修改doStuff()以引入參數。

function doStuff(el) { 
    console.log('DoStuff called. Received element:'); 
    console.log(e); 
}