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'));
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c4d6-4d99f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c4d6-4d99f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?