使用 jQuery 代码,例如:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
myfunction
使用 jQuery 时如何传递参数?
使用 jQuery 代码,例如:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
myfunction
使用 jQuery 时如何传递参数?
最简单的方法是这样做(假设您不希望将任何事件信息传递给函数)...
$("#myid").click(function() {
myfunction(arg1, arg2);
});
这将创建一个匿名函数,在click
触发事件时调用该函数。这将依次调用myfunction()
您提供的参数。
如果要保留ThisBinding
(this
调用函数时的值,设置为触发事件的元素),则使用call()
.
$("#myid").click(function() {
myfunction.call(this, arg1, arg2);
});
您不能按照示例所述的方式直接传递引用,或者它的单个参数将是jQuery event
object。
如果确实想传递引用,则必须利用 jQuery 的proxy()
函数(它是 的跨浏览器包装器Function.prototype.bind()
)。这使您可以传递参数,这必将之前的event
说法。
$("#myid").click($.proxy(myfunction, null, arg1, arg2));
在这个例子中,myfunction()
将与要执行其ThisBinding
完整的(null
不是一个对象,所以正常this
从而引发所使用的事件的元素的值),其中参数(按顺序)沿arg1
,arg2
并且最后jQuery的event
对象,则可以忽略如果不需要(甚至不要在函数的参数中命名)。
您也可以使用 jQueryevent
对象data
来传递数据,但这需要修改myfunction()
以通过event.data.arg1
(不是您的问题提到的函数参数)来访问它,或者至少引入一个手动代理函数,如前一个示例或生成的一个使用后一个例子。
$("#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'
});
还允许您使用 on 和 off 方法绑定和取消绑定特定的事件处理程序。
例子:
$("#myid").off('click', myfunction);
这将从#myid 解除绑定 myfunction 处理程序
虽然您当然应该使用 Alex 的答案,但原型库的“绑定”方法已在 Ecmascript 5 中标准化,并且很快将在浏览器中本地实现。它是这样工作的:
jQuery("#myid").click(myfunction.bind(this, arg1, arg2));
旧线程,但用于搜索目的;尝试:
$(selector).on('mouseover',...);
...并检查“数据”参数:http : //api.jquery.com/on/
例如:
function greet( event ) {
alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {name: "Karl"}, greet );
$( "button" ).on( "click", {name: "Addy"}, greet );
已经有很好的答案,但无论如何,这是我的两分钱。您还可以使用:
$("#myid").click({arg1: "foo", arg2: "bar"}, myfunction)
听者看起来像:
function myfunction(event){
alert(event.data.arg1);
alert(event.data.arg2);
}