With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
如何在使用jQuery时将参数传递给myfunction
?
With jQuery code like:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
如何在使用jQuery时将参数传递给myfunction
?
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);
});
这将创建一个匿名函数,在触发click
事件时调用该函数.这将依次调用myfunction()
和您提供的参数.
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);
});
您不能按照示例中的方式直接传递引用,否则它的单个参数将是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美元.
在本例中,myfunction()
的ThisBinding
完好无损地执行(null
不是对象,因此使用触发事件的元素的正常this
值),以及参数(按顺序)arg1
、arg2
,最后是jQuery event
对象,如果不需要它,您可以忽略它(甚至不要在函数的参数中命名它).
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.