JS AddEventListener call parameter function

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.