2011-01-14 32 views
2

在所有的jQuery的例子,我看到這樣的代碼:jQuery的:添加現有功能的jQuery的事件

$('.menu a').each(function(){ 
$(this).animate({paddingLeft: $(this).width()}, 200); 
}); 

他們在這裏做什麼是「對飛」創建一個函數(就是所謂的匿名委託?)

但如果我有一個現有的函數,它想要有權訪問$(this)呢?

比方說,我有這樣的功能:

function doAnimate(ctl){ 
    //do something here 
{ 

我如何使用jQuery的聲明功能?

我想問的原因是我想在更多的jquery語句中使用這個函數,而且我不想多次輸入匿名代理。

我試過這個,但是這給了我一個錯誤:

$("#<%=txtReceiverEmailEcard1.ClientID %>").blur(blurWatermark($(this), 'Your email address')); 
+0

正確,'即時'是匿名函數 – Tx3 2011-01-14 09:00:22

回答

5

這是從jQuery API documentation

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

而且方法的簽名是

.each(function(index, Element))

function(index, Element)A function to execute for each matched element.

然後,您可以編寫

$('.menu a').each(myFunction) 

function myFunction(index, Element) { 
    alert(this); /* this points to the element */ 
} 

這基本上意味着你可以得到所有一種很好的信息(如索引)到你的回調。

2

簡單:

$('.menu a').each(doAnimate) 

只要一個匿名函數的工作,一提到一個「正常」的一個作品一樣好。 :)然後,你需要使用的功能參數,如

function doAnimate (index, elem) { 
    $(elem).animate({paddingLeft: $(elem).width()}, 200); 
} 
+0

,我可以通過`$(this)`嗎? – Michel 2011-01-14 09:01:40

+0

我想問的原因是它現在不工作,我編輯了問題 – Michel 2011-01-14 09:02:18

1

你可以嘗試像

$('.menu a').each(function(){ 
    doAnimate($(this)); 
}); 

的東西,如果它的可重複使用的一個,然後制定一個plugin,你可以很容易地使用jQuery對象相關聯。