JS element event bindings and unbinding

Source: Internet
Author: User

There are 3 ways to bind an event to an element:

1, the most common way of binding:

document.getElementById ("Btn"). onclick=function() {};

2, non-IE browser element.addeventlistener (type,fn,false)

(Boolean ====true means capture, false means bubbling, usually false):

document.getElementById ("Btn"). AddEventListener ("click", Function () {};false);

3,IE browser event binding element.attachevent ("on" +TYPE,FN)

document.getElementById ("Btn"). Attachevent ("onclick",function() {});

================== compatible code for element binding events: =======================

1     function AddEventListener (ELEMENT,TYPE,FN) {2                 if (element.addeventlistener) {3                     Element.addeventlistener (Type,fn,false); 4                 }else if (element.attachevent) {5                     element.attachevent ("on" +TYPE,FN), 6                 }else{7                     element["on" +type ]=FN; 8                 } 9             }

There are 3 ways to unbind an element:

1, Ordinary way:

document.getElementById ("Btn"). Onclick=null;

2, non-IE browser element.removeeventlistener (type,fname,false)

(Boolean ====true means capture, false means bubbling, usually false):

document.getElementById ("Btn"). RemoveEventListener ("click", Fname,false);

3,IE browser element.detachevent ("on" +type,fname)

document.getElementById ("Btn"). DetachEvent ("onclick", fName);

================== compatible code for an element to unbind an event: =======================

1     functionRemoveEventListener (element,type,fname) {2                 if(element.removeeventlistener) {3Element.removeeventlistener (Type,fname,false);4}Else if(element.detachevent) {5Element.detachevent ("on" +type,fname);6}Else{7element["on" +type]=NULL;8                 }9             } 

JS element event bindings and unbinding

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.