With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
How do I pass arguments to myfunction
while using jQuery?
javascriptjquery
With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
How do I pass arguments to myfunction
while using jQuery?
Best Answer
The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...
jsFiddle.
This create an anonymous function, which is called when the
click
event is triggered. This will in turn callmyfunction()
with the arguments you provide.If you want to keep the
ThisBinding
(the value ofthis
when the function is invoked, set to the element which triggered the event), then call the function withcall()
.jsFiddle.
You can't pass the reference directly in the way your example states, or its single argument will be the jQuery
event
object.If you do want to pass the reference, you must leverage jQuery's
proxy()
function (which is a cross browser wrapper forFunction.prototype.bind()
). This lets you pass arguments, which are bound before theevent
argument.jsFiddle.
In this example,
myfunction()
would be executed with itsThisBinding
intact (null
is not an object, so the normalthis
value of the element which triggered the event is used), along with the arguments (in order)arg1
,arg2
and finally the jQueryevent
object, which you can ignore if it's not required (don't even name it in the function's arguments).You could also use use the jQuery
event
object'sdata
to pass data, but this would require modifyingmyfunction()
to access it viaevent.data.arg1
(which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.