开发者

Jquery: add existing function to an Jquery event

in all jquery examples i see t开发者_运维百科his kind of code:

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

What they do here is create a function 'on the fly' (is that called an anonymous delegate?)

but what if i have an existing function, which wants to have access to the $(this) also?

let's say i have this function:

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

How can i use that function in the jquery statement?

Reason i ask is that i want to use this function in more jquery statements, and i don't want to type the anonymous delegate multiple times.

I've tried this, but that gives me an error:

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


This is from the 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.

And the signature of the method is

.each( function(index, Element) )

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

You can then write

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

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

That basically means that you can get all kind of nice information (like index) to your callback.


Simply:

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

Wherever an anonymous function works, a reference to a "normal" one works just as well. :) Then you need to use the function parameters like

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


You can try something like

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

If its a reusable one then develop a plugin that you can easily associate with jQuery objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜