开发者

jQuery: How do you pass $(this) as function parameter?

All jQuery examples I see has in-line functions.

If the function is pretty long, or if the function is reu开发者_如何学Gosable, I may want to separate the function.

For example, how can I turn this

$('#myElement').click(function(){
  $(this).addCss('clicked');
})

into something like this

$('#myElement').click(ElementClicked($(this))

function ElementClicked(???){
  ???.addCss('clicked');
}

Thanks!


This won't work:

$('#myElement').click(ElementClicked($(this)));

This is executing the function ElementClicked() with whatever this is at the time of writing, and binds the return value of ElementClicked() to the click event. Which in this case is nothing.

You'll need to pass a function to a click event, like so:

$('#myElement').click(function () { ElementClicked($(this)); });

This makes a(n anonymous) function, which will be bound to the click event, and the function calls ElementClicked() when run, passing this. The function ElementClicked can be defined as:

function ElementClicked(elem) {
  elem.addClass('clicked');
}

As you will notice though, this inside the function that is bound to the event will be the clicked element. So instead of making a function wrapper that calls a function passing the element, you can just abbreviate it like so:

$('#myElement').click(ElementClicked);

function ElementClicked() {
  $(this).addClass('clicked');
}

Notice that the function is passed to click() like a variable instead of being executed immediately, because there are no brackets () following it.

And BTW, you probably mean addClass instead of addCss.


It's just an expression; you pass it just like you'd pass (x + 1) or whatever. Give it a name in your function and you're good to go:

function elementClicked(banana) {
    banana.addClass('clicked');
}


$('#myElement').click(function(){
  ElementClicked($(this)); 
})

function ElementClicked(el){
  el.addCss('clicked');
}


it is better to seperate between

document.elementByID("div1")

$("#div1")

so I prefer to attatch 'j'

jElement = $("#div1")

element = document.elementByID("div1")

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜