When I have
$('#div').click(function(someVar){//do something with soneVar});
but I want to have a named callback function, am I palcing the passed someVar
correctly?
$('#div').click(someFunction(someVar));
function someFunction(someVar){}
Both of your examples are wrong.
Your first example creates a parameter to the callback method named someVar
; it will become the event
object that jQuery passes to the handler method.
The second example calls the method immediately, then passes its result to the click
method as an event handler.
You you need to pass a function expression that calls your function with a parameter from the outer scope (using a closure):
$('#div').click(function() { someFunction(someVar); });
The click
callback function will be passed a jQuery Event object, not someVar
.
You have to call your function yourself within the callback function.
$('#div').click(function(ev) {
someFunction(someVar);
}
function someFunction(someVar) {
...
}
Alternatively, do:
$('#div').click({someVar: someVar}, someFunction);
function someFunction(ev) {
// your var is now in ev.data.someVar
}
Look into passing the arguments as event data to the click event (or any event with jQuery): http://api.jquery.com/click/
精彩评论