With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
How do I pass arguments to myfunction while using jQuery?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
clickevent is triggered. This will in turn callmyfunction()with the arguments you provide.If you want to keep the
ThisBinding(the value ofthiswhen 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
eventobject.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 theeventargument.jsFiddle.
In this example,
myfunction()would be executed with itsThisBindingintact (nullis not an object, so the normalthisvalue of the element which triggered the event is used), along with the arguments (in order)arg1,arg2and finally the jQueryeventobject, 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
eventobject’sdatato 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.