使用jQuery代码,例如:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
myfunction在使用jQuery时如何将参数传递给?
使用jQuery代码,例如:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
myfunction在使用jQuery时如何将参数传递给?
Answers:
最简单的方法是这样做(假设您不希望将任何事件信息传递给该函数)...
$("#myid").click(function() {
myfunction(arg1, arg2);
});
这将创建一个匿名函数,click事件触发时将调用该匿名函数。这将依次调用myfunction()您提供的参数。
如果要保留ThisBinding(this调用函数时的值,设置为触发事件的元素),请使用调用函数call()。
$("#myid").click(function() {
myfunction.call(this, arg1, arg2);
});
您不能以示例所陈述的方式直接传递引用,否则它的单个参数将是jQuery eventobject。
如果您确实想传递引用,则必须利用jQuery的proxy()功能(这是的跨浏览器包装Function.prototype.bind())。这使您可以传递参数,这必将之前的event说法。
$("#myid").click($.proxy(myfunction, null, arg1, arg2));
在此示例中,myfunction()将ThisBinding完整无缺地执行(null不是对象,因此将this使用触发事件的元素的常规值)以及参数(按顺序)arg1,arg2最后是jQuery event对象,您可以忽略该参数如果不是必需的(甚至不要在函数的参数中命名)。
您还可以使用jQuery event对象data来传递数据,但这需要进行修改myfunction()才能通过进行访问event.data.arg1(不是像您提到的问题那样的函数参数),或者至少要引入手动代理函数(如前一个示例或生成的一个)使用后一个示例。
myfunction(this, arg1, arg2)从匿名处理程序调用。然后您的函数就可以了myfunction(el, arg1, arg2) { alert($(el).val()); }
myfunction.call(this, arg1, arg2)。
$("#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);
这将使myfunction处理程序与#myid解除绑定
尽管您当然应该使用Alex的答案,但是Ecmascript 5中已对原型库的“绑定”方法进行了标准化,并将很快在本机浏览器中实现。它是这样的:
jQuery("#myid").click(myfunction.bind(this, arg1, arg2));
this如果使用此方法,将设置为其他上下文,例如,在该上下文中将bind()其设置为this(全局)可能会导致单击处理程序具有window对象this而不是对#myid元素的引用?
people reading my answers are smart enough to figure these details out themselves,而不是Ecmascript。
旧线程,但出于搜索目的;尝试:
$(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 );