Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - How can I pass arguments to event handlers in jQuery?

With jQuery code like:

$("#myid").click(myfunction);

function myfunction(arg1, arg2) {/* something */}

How do I pass arguments to myfunction while using jQuery?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...