Look at this code first.
1 function ABC (key) {2 console.log (key); 3 }4for (let i=0;i<oinput.length;i++) {5 oinput[i]. AddEventListener (' Focus ', ABC (i)); 6 }
You will find that the focus operation has not yet been performed, and the value of I has been printed sequentially.
How to pass the parameter function without being executed immediately, method one: Bind an anonymous function to AddEventListener.
Element.addeventlistener (' mouseover ',function(e,some) {fn (e,some);});
Tip: You cannot use RemoveEventListener to remove an event if you bind an anonymous function.
Method Two: Bind method. Bind is similar to call/apply and is usually used to change the direction of this function, but unlike the latter, no additional () operator in Bind will be immediately functional. For this feature, it is what we need here.
function ABC (key) { console.log (key);} for (Let i=0;i<oinput.length;i++) { Oinput[i].addeventlistener (' Focus ', Abc.bind ( this
Tip:bind is a method in ES5, incompatible with IE8. If compatibility is required, there is a corresponding polyfill on the MDN.
JS AddEventListener call parameter function