[英]Passing a function with parameter to event handler
Let's say I have the following code: 假设我有以下代码:
$('#from').focus(listExpand(1));
$('#to').focus(listExpand(3));
It's not working as I expected. 它没有按我预期的那样工作。 I think that it works wrong due to the fact that I'm passing a function result but not the function itself.
我认为这是错误的,因为我传递了函数结果而不是函数本身。
So the right syntax would be: 因此正确的语法是:
$('#from').focus(listExpand); // no brackets and no parameters
But in this case I can not pass any parameters to a function :( 但是在这种情况下,我无法将任何参数传递给函数:(
How can I implement the subject? 如何实施该主题?
below will work. 下面将工作。 use this.
用这个。
$('#from').focus(function() {listExpand(1) });
$('#to').focus(function(){listExpand(3);})
I found other cool way also that @sudher mentioned. 我也发现了@sudher提到的其他很酷的方法。 You can check it working in http://jsfiddle.net/kvHDA/
您可以在http://jsfiddle.net/kvHDA/中检查其是否正常运行
Sample Code 样例代码
$('#from').focus({x: 1},myfunc);
function myfunc( e){
alert(e.data.x);
}
Wrap the call to listExpand
in a separate function definition: listExpand
的调用listExpand
在单独的函数定义中:
$('#from').focus(function(){ listExpand(1); });
$('#to').focus(function(){ listExpand(3); })
If a data argument is provided to .on() and is not null or undefined, it is passed to the handler in the event.data property each time an event is triggered.
如果将数据参数提供给.on(),并且不为null或未定义,则每次触发事件时,该参数都会传递给event.data属性中的处理程序。
$('#from').on("focus" , {id:1} , listExpand);
$('#to').on("focus" , {id:3} , listExpand);
function listExpand(event){
console.log(event.data.id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.