Encapsulation of adding and deleting native js events

Source: Internet
Author: User

Add or delete events using attachEvent and detachEvent in IE browser. In other standard browsers, addEventListener and removeEventListener are used. The following encapsulates the addition and deletion of events. Check the Code directly!

/*** @ Description event binding, compatible with various browsers * @ param target * event trigger object * @ param type * event * @ param func * event processing function */function bind (target, type, func) {if (target. addEventListener) {// non-ie and ie9target. addEventListener (type, func, false);} else if (target. attachEvent) {// ie6 to ie8target. attachEvent ("on" + type, func);} else {target ["on" + type] = func; // ie5}/*** @ description event removed, compatible with various browsers * @ param target * event trigger object * @ param type * event * @ param func * event processing function */function unbind (target, type, func) {if (target. removeEventListener) {target. removeEventListener (type, func, false);} else if (target. detachEvent) {target. detachEvent ("on" + type, func);} else {target ["on" + type] = null ;}}

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.