简体   繁体   中英

javascript - Pass Event and Parameters to function called with addEventListener

window.addEventListener("keyup", eventkeyup(event, something), false);

    function eventkeyup(event, something) {

    //could not be able to get the event object here.

}

How can I access Event in this function?

Pass function itself, not return value of it which is undefined in your case.

window.addEventListener("keyup", eventkeyup(something), false);

function eventkeyup(something) {
    return function(event){
       // you have event and something here
    }
}

You can't call a function while you use it inside addEventListener. You can only pass the reference of that particular function. For your desired situation you can define a function inside the addEventListener and in that function just call your desired function and pass the event and some other variable as arguements.

Check if this helps

 //script let div = document.getElementById("demo"); let someText = "hello\n World\n how are you doing? "; div.addEventListener("click", function(event){ eventkeyup(event, someText); }) function eventkeyup(event, something) { console.log(something); console.log(event); }
 /*css*/ #demo{ width:250px; height:200px; /*border:1px solid dodgerblue;*/ background-color:dodgerblue; color:white; text-align:justified; }
 <!--html--> <p>click on the below div and wait for sometimes</p> <p> in the console if you only see the event object scroll up</p> <div id = "demo"> <div>

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