简体   繁体   中英

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. You can check it working in 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:

$('#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.

$('#from').on("focus" , {id:1} , listExpand);
$('#to').on("focus" , {id:3} , listExpand);

function listExpand(event){

   console.log(event.data.id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM