The difference between AddEventListener () and attachevent ()

Source: Internet
Author: User

To do the front-end development engineer, the most tragic one is too browser-compatible problem, there are two ways to add events, in order to add the same event method, we > have to re-write a common add event function, thanks to the predecessors to help us do this thing

function addEvent(elm, evType, fn, useCapture) {if (elm.addEventListener) {elm.addEventListener(evType, fn, useCapture);//DOM2.0return true;}else if (elm.attachEvent) {var r = elm.attachEvent(‘on‘ + evType, fn);//IE5+return r;}else {elm[‘on‘ + evType] = fn;//DOM 0}}

function addevent (element, type, handler) {//Assign a unique idif for each event handler (!handler.$ $guid) handler.$ $guid = addevent.guid++ ;//Create a hash table for the event type of the element if (!element.events) element.events = {};//for each "element/event" pair creates an event handler for the hash table var handlers = element.events[ Type];if (!handlers) {handlers = Element.events[type] = {};//Stores existing event handlers (if any) if (element["on" + type]) {Handlers[0] = Elem Ent["on" + Type];}} Save event handlers to hash table handlers[handler.$ $guid] = handler;//Assign a global event handler to do all the work element["on" + type] = handleevent;};/ /Counter used to create a unique id addevent.guid = 1;function removeevent (element, type, handler) {//Remove the event handler function from the hash table if (element.events && Amp Element.events[type]) {delete element.events[type][handler.$ $guid];}}; function Handleevent (event) {var returnvalue = true;//Captured Event object (ie uses global event object) event = Event | | fixevent (window.event);// A reference to the hash table that gets the event handler var handlers = this.events[event.type];//performs each handler function for (var i in handlers) {this.$ $handleEvent = handlers[ I];if (this.$ $handleEvent (event) = = = False) {returnvalue = false;}} Return returnvalue;};//Add some "missing" function Fixevent (event) {//Add Standard method Event.preventdefault = Fixevent.preventdefault) for IE events object; Event.stoppropagation = Fixevent.stoppropagation;return event;}; Fixevent.preventdefault = function () {this.returnvalue = false;}; Fixevent.stoppropagation = function () {this.cancelbubble = true;};

The function is very strong, solve the IE this point problem, the event is always passed as the first parameter, cross-browser is even more. In general we add the event in JS, this is the

obj.onclick=method

This way of binding events is compatible with mainstream browsers, but what if one element is added multiple times the same event?

obj.onclick=method1;obj.onclick=method2;obj.onclick=method3;

If this is the case, then only the last bound event, here is method3 will be executed, this time we can not use the onclick such a notation, the main > Corner change, in IE we can use the Attachevent method

//object.attachEvent(event,function);btn1Obj.attachEvent("onclick",method1);btn1Obj.attachEvent("onclick",method2);btn1Obj.attachEvent("onclick",method3);

The use of the format is preceded by the event type, note that the need to add on, such as Onclick,onsubmit,onchange, the order of execution is

Method3->method2->method1

Unfortunately this Microsoft private method, Firefox and other browsers are not supported, fortunately they all support the standard AddEventListener method

//element.addEventListener(type,listener,useCapture);btn1Obj.addEventListener("click",method1,false);btn1Obj.addEventListener("click",method2,false);btn1Obj.addEventListener("click",method3,false);

Execution order is method1->method2->method3

Finally contribute a version of the HTML5 workgroup:

var addEvent=(function(){if(document.addEventListener){return function(el,type,fn){if(el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn);}}else{el.addEventListener(type,fn,false);}};}else{return function(el,type,fn){if(el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn);}}else{el.attachEvent(‘on‘+type,function(){return fn.call(el,window.event);});}};}})();

Perhaps the attentive reader has discovered that the attachevent of IE and the standard of addeventlistener binding multiple events are executed in a different order.

We all know that the use of events is when an event (condition) is triggered to execute a function, especially JavaScript, in the context of the popular Ajax catalysis, to understand the JavaScript event usage is more important, Here is a general introduction to the event usage of Avascript.

How to use AddEventListener:

target.addeventlistener (type, listener, Usecapture);

  Type: String, event name, does not contain "on", such as "click", "MouseOver", "KeyDown" and so on.   listener: Implements a EventListener interface or a function in JavaScript.   usecapture: Use snapping, generally false.

example:

    
in IE:

Target.attachevent (type, listener); Target: Documentation node, document, window, or XMLHttpRequest. Type: String, event name, including "on", such as "onclick", "onmouseover", "onkeydown" and so on. Listener: Implements a EventListener interface or a function in JavaScript. For example: document.getElementById ("TXT"). Attachevent ("onclick", function (event) {alert (event.keycode);});

Internet Explorer and IE also support the removal of the specified event, the purpose is to remove the set of events, the format is as follows:
removeEventListener(event,function,capture/bubble);  
Windows IE has the following format:
detachEvent(event,function); target.addEventListener(type, listener, useCapture);  target 文档节点、document、window 或 XMLHttpRequest。 type 字符串,事件名称,不含“on”,比如“click”、“mouseover”、“keydown”等。   

Listener implements a EventListener interface or a function in JavaScript.

Usecapture whether to use snapping, see the next event stream after the end of the understanding, generally with false

When an event is triggered, an event object is passed to the handler.

Like what:

document.getElementById("testText").addEventListener("keydown", function (event) { alert(event.keyCode); }, false);   

Adapt to the browser version is different, at the same time in the use of the process to note: attachevent method button onclick ie using the AddEventListener method button Click in the Fox use

The principle of the use of both: the execution of the priority can be different, the following examples are explained below: Attachevent method, for an event to attach additional processing events. (Mozilla series not supported) The AddEventListener method is used for example in the Mozilla series:

document.getElementById("btn").onclick = method1;  document.getElementById("btn").onclick = method2;  document.getElementById("btn").onclick = method3;

If this is the case, then only MEDHOT3 will be executed as follows:

In the case of the Mozilla series, this method is not supported and requires

addEventListener var btn1Obj = document.getElementById("btn1"); //element.addEventListener(type,listener,useCapture); btn1Obj.addEventListener("click",method1,false); btn1Obj.addEventListener("click",method2,false); btn1Obj.addEventListener("click",method3,false);  

Event binding compatibility Function:

    if(div.attachEvent){       div.attachEvent(‘事件名‘,function(){})    }else{      div.addEventListener(‘事件名‘,function(){},false)    };

The difference between AddEventListener () and attachevent ()

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.