General AddEventListener Method

Source: Internet
Author: User

Suppose we need to add a click event handler for a <a id= "Aele" href= "http://www.baidu.com"/>, which is generally the case:

var Aele = document.getElementById (' Aele '); Aele.addeventlistener (' Click ', Function (e) {    console.log (e.target);    E.preventdefault ();});

If we use jquery, we can make it easier:

$ (' #aEle '). Click (function (e) {    console.log (e.target);    E.preventdefault ();});

However, the above two code is invalid in the version of IE browser IE8 and below.

In IE8 and the following IE browser, we must use E.srcelement to replace the e.target, there is no Preventdefault method, we can only set E.returnvalue=false to achieve the same purpose. The following is a common method of handling:

var Aele = document.getElementById (' Aele '); AddEventListener (Aele, ' click ', Function (e) {console.log (e); E.preventdefault ();}); function AddEventListener (Element,event,handler) {if (Element.addeventlistener) {Element.addeventlistener (event, handler);} else if (element.attachevent) {element.attachevent (' on ' +event, function (e) {e.preventdefault = function () { E.returnvalue = false;}; Handler.call (element, e);});}

General AddEventListener Method

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.