简体   繁体   中英

Passing a parameter to a function, while keeping the event handler

this might have been asked, but doing a brief search, I couldn't find an answer.

I am creating a function to handling user events, and I don't know how to pass a parameter into the function, without ruining the event handler.

Here is my code:

function keydown(e) {
e = e || window.event;
if (e.keyCode == '38' || e.keycode == '40' || e.keyCode == '37' || e.keyCode == '39')
    e.preventDefault();

switch(e.keyCode){
    case 38: //Up
        console.log('UP');
        break;
    case 40: //Down
        console.log('DOWN');
        break;
    case 37: // Left
        console.log('LEFT');
        break;
    case 39: //Right
        console.log('RIGHT');
        break;
}}

I would like something like this:

    function keydown(e, myParam) {
        console.log(myParam); // Console logging the second parameter
        e = e || window.event;
        if (e.keyCode == '38' || e.keycode == '40' || e.keyCode == '37' || e.keyCode == '39')
            e.preventDefault();

        switch(e.keyCode){
            case 38: //Up
                console.log('UP');
                break;
            case 40: //Down
                console.log('DOWN');
                break;
            case 37: // Left
                console.log('LEFT');
                break;
            case 39: //Right
                console.log('RIGHT');
                break;
        }
    }

Anybody got any suggestions?

You can use a closure:

function keydown(param) {
  return function(e) {
    console.log(param)
    ...
  }
}

elem.addEventListener('keydown', keydown(param))

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