2011-01-14 31 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对象相关联。