如何在jQuery中将参数传递给事件处理程序? [英] How can I pass arguments to event handlers in jQuery?
问题描述
使用jQuery代码:
With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
如何在使用jQuery时将参数传递给 myfunction
?
How do I pass arguments to myfunction
while using jQuery?
推荐答案
最简单的方法是这样做(假设您不希望任何事件信息传递给函数)...
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 。
这会创建一个匿名函数,在点击
事件被触发时调用。这将依次使用您提供的参数调用 myfunction()
。
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.
如果您想保留 ThisBinding
(<$ c $的值c>这个当调用函数时,设置为触发事件的元素),然后用 call()
。
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 。
您无法以示例所声明的方式直接传递引用,或者其单个参数将是 jQuery event
object 。
You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event
object.
如果你做想传递引用,你必须利用jQuery的 proxy()
function(这是 Function.prototype.bind()
)。这允许您传递参数,这些参数在 事件
参数之前绑定。
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 。
在此示例中, myfunction()
将以<$ c执行$ c> ThisBinding 原封不动( null
不是对象,所以正常此
值触发事件的元素的使用),以及参数(按顺序) arg1
, arg2
最后jQuery 事件
对象,如果不需要,可以忽略它(甚至不要在函数的参数中命名)。
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).
您还可以使用jQuery 事件
对象的 数据
传递数据,但这需要修改 myfunction()
才能通过 event.data.arg1
(这不是函数参数,就像你的问题提到的那样),或者至少引入了像前一个例子那样的手动代理函数o使用后一个例子生成一个。
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.
这篇关于如何在jQuery中将参数传递给事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!