With jQuery code like:
$("#myid").click(myfunction); function myfunction(arg1, arg2) {/* something */}
How do I pass arguments to myfunction
while using jQuery?
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function. The event object provides various useful information about the event.
The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...
$("#myid").click(function() { myfunction(arg1, arg2); });
jsFiddle.
This create an anonymous function, which is called when the click
event is triggered. This will in turn call myfunction()
with the arguments you provide.
If you want to keep the ThisBinding
(the value of this
when the function is invoked, set to the element which triggered the event), then call the function with call()
.
$("#myid").click(function() { myfunction.call(this, arg1, arg2); });
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 for Function.prototype.bind()
). This lets you pass arguments, which are bound before the event
argument.
$("#myid").click($.proxy(myfunction, null, arg1, arg2));
jsFiddle.
In this example, myfunction()
would be executed with its ThisBinding
intact (null
is not an object, so the normal this
value of the element which triggered the event is used), along with the arguments (in order) arg1
, arg2
and finally the jQuery event
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's data
to pass data, but this would require modifying myfunction()
to access it via event.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.
$("#myid").on('click', {arg1: 'hello', arg2: 'bye'}, myfunction); function myfunction(e) { var arg1 = e.data.arg1; var arg2 = e.data.arg2; alert(arg1); alert(arg2); } //call method directly: myfunction({ arg1: 'hello agian', arg2: 'bye again' });
Also allows you to bind and unbind specific event handlers using the on and off methods.
Example:
$("#myid").off('click', myfunction);
This would unbind the myfunction handler from #myid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With