【发布时间】:2010-11-02 00:50:27
【问题描述】:
使用 jQuery 代码如下:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
如何在使用 jQuery 时将参数传递给 myfunction?
【问题讨论】:
标签: javascript jquery
使用 jQuery 代码如下:
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
如何在使用 jQuery 时将参数传递给 myfunction?
【问题讨论】:
标签: javascript 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 对象,如果不需要,可以忽略(甚至不要在函数的参数中命名)。
您也可以使用 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 );
【讨论】:
已经有很好的答案,但无论如何,这是我的两分钱。您还可以使用:
$("#myid").click({arg1: "foo", arg2: "bar"}, myfunction)
监听器看起来像:
function myfunction(event){
alert(event.data.arg1);
alert(event.data.arg2);
}
【讨论】:
简单:
$(element).on("click", ["Jesikka"], myHandler);
function myHandler(event){
alert(event.data); //passed in "event.data"
}
【讨论】: