The problem of adding formal parameters to functions bound by addEventListener

for example, this code:

 function add() {
    console.log("add")
}
document.querySelector("-sharpipt").addEventListener("click",add);

what I need now is to take parameters in the add function, that is,

 function add(val) {
    console.log("add"+val)
}
document.querySelector("-sharpipt").addEventListener("click",add("argument"));

it"s not right to write this. How can I pass in the function form of add with parameters?

Mar.30,2021

simple words: document.querySelector ('- sharpipt'). AddEventListener ('click',function () {add (' argument');});
fancy a little bit, you can use the function Corey


because the second argument to the listener function must be a function, either a layer of function is wrapped around it, or the add method returns a function.

but in fact, neither of these points is recommended, because the returned function has no variable reference to it and cannot unlisten

.

it is best to assign the resulting function to a variable and use this variable as a parameter


just return a function

 function add(val) {
    return function(e) {
       console.log(val)
       console.log(e)
    }
}
document.querySelector('-sharpipt').addEventListener('click',add('argument'));
Menu