Javascript event Summary

Source: Internet
Author: User
Document directory
  • Dean Edwards's solution: addevent/removeevent Library
  • Event bubbling

    • Different Phases of events
    • Cancel event bubble
    • Reload default browser behavior
  • Common event objects
    • This
    • Event object
  • Event binding
    • Traditional Dom binding
    • W3C standard binding
    • IE binding
  • Niu Ren's Solution
I. Event bubbling 1.1 Different Stages of an event

Javascript events are executed in two phases: capture and bubbling.

For example, if the link to the anchor #1.1 in the DOM structure is clicked, the click processing function of document> body> ul> LI> A is triggered in turn. This completes the capture phase. When this stage is complete, start the bubble stage, in the ascending order of arrows. All event processing functions are triggered. If you are interested, click here to see the dynamic process.

Let's make a slight change to the above Code. If alert is used, because the effect switching in the demo is too fast, we will take a little bit of experience. [Note: The subscribed events are in the bubble phase and are most commonly used, because IE does not support the subscription capture phase time. There are also special opera, which often involves some features to the Firefox system, and occasionally has some features such as IE ]. This article also helps deepen understanding

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" </P> <p> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> </P> <p> <HTML xmlns = "http://www.w3.org/1999/xhtml" lang = "ZH" XML: lang = "ZH"> </P> <p> <pead> </P> <p> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> </P> <p> <meta name =" Developer "content =" realazy "/> </P> <p> <title> bubble in Javascript dom </title> </P> <p> <style ty Pe = "text/CSS" Media = "screen"> </P> <p> Div * {display: block; margin: 4px; padding: 4px; Border: 1px solid white ;}</P> <p> textarea {width: 20em; Height: 2em ;} </P> <p> </style> </P> <p> <SCRIPT type = "text/JavaScript"> </P> <p> // <! [CDATA [</P> <p> function Init () {</P> <p> var log = document. getelementsbytagname ('textarea ') [0]; </P> <p> var all = document. getelementsbytagname ('div ') [0]. getelementsbytagname ('*'); </P> <p> for (VAR I = 0, n = All. length; I <n; ++ I) {</P> <p> All [I]. onmouseover = function (e) {<br/> alert ('the cursor enters: '+ this. nodename); <br/> This. style. border = '1px solid red'; </P> <p> log. value = 'cursor: '+ this. noden Ame; </P> <p >}; </P> <p> All [I]. onmouseout = function (e) {<br/> alert ('the cursor is removed now: '+ this. nodename); <br/> This. style. border = '1px solid white'; </P> <p >}; </P> <p >}</P> <p> var all2 = document. getelementsbytagname ('div ') [1]. getelementsbytagname ('*'); </P> <p> for (VAR I = 0, n = all2.length; I <n; ++ I) {</P> <p> all2 [I]. onmouseover = function (e) {</P> <p> This. style. border = '1px solid red'; </P> <p> If (e )/ /Stop event bubbling </P> <p> E. stoppropagation (); </P> <p> else </P> <p> window. event. cancelbubble = true; </P> <p> log. value = 'cursor: '+ this. nodename; </P> <p >}; </P> <p> all2 [I]. onmouseout = function (e) {</P> <p> This. style. border = '1px solid white'; </P> <p> }; </P> <p >}</P> <p> window. onload = Init; </P> <p> //]> </P> <p> </SCRIPT> </P> <p> </pead> </P> <p> <body> </P> <p> <p> bubble in Javascript DOM </p> </P> <p> dom The structure of the tree is: </P> <p> <PRE> <code> </P> <p> ul </P> <p>-LI </P> <p >-A </P> <p>-span </P> <p> </code> </PRE> </P> <p> <div> </P> <p> <ul> </P> <p> <li> <a href = "#"> <span> bubbllllllllllllllle </span> </a> </Li> </P> <p> <li> <a href = "#"> <span> bubbllllllllllllllle </span> </a> </LI> </P> <p> </ul> </P> <p> </div> </P> <p> <textarea> </P> <p> move the cursor to any sub-element of ul, if you do not stop the bubble, the <code> Mouseover </code> event is defined from ul to span. This event increases by UL The element to Ul will have red edges. </P> <p> <div> </P> <p> <ul> </P> <p> <li> <a href = "# "> <span> bubbllllllllllllllllle </span> </a> </LI> </P> <p> <li> <a href =" # "> <span> bubbllllllllllllle </span> </a> </LI> </P> <p> </ul> </P> <p> </div> </P> <p> <p> if you stop bubbling, events do not rise, so we can get precise mouse entry elements. </P> <p> </body> </P> <p> </ptml>

1.2 cancel event bubbling

In fact, 1.1 of the Code already contains the code for canceling event bubbles. Here we specifically propose to make it more compatible and elegant.

1 function stopbubble (e ){
2 If (E & E. stoppropagation ){
3 E. stoppropagation (); // The event object e is passed in and supports the W3C standard stoppropagation ()
4} else {
5 window. event. cancelbubble = true; // for IE
6}
7}

[Note]: we cannot simply see that the event object is passed into the non-IE browser, because sometimes we use the 3.1 Method to bind events, it is very likely that a window will be passed in at this time. event reference.

1.3 reload default browser behavior

For HTML elements with a tag and Other Default behaviors (such as jump to a URL), we may want some of the features of a. clicking a certain A will not jump, and we can reload its default behavior.

function stopDetault(e) {
if (e&&e.preventDetault) {
e.preventDefault();
} else {
window.event.returnValue = false;
}
return false;
}

Usage:

document.getElementById("##").onclick = function (e) {
//do sth.
return stopDetault(e);
}

We also use the following methods to block default actions, so you can understand how to block the event handler function from returning false.

<a href="javascript:alert('clicked');return false;">a link without redirect action</a>

  

In the book "Pro JavaScript techniques" [US John resig], 95% of the cases mentioned prevent the default behavior from being valid, but occasionally it also fails because the behavior is determined by the browser, this is especially true for text domain attacks and IFRAME attacks. In addition, there should be no major problems. This is a good book to learn JavaScript. Recommended.

Ii. Common event object 2.1 This

This keyword is a variable in Javascript that provides reference to the current object. When binding events, this usually refers to the current element, but there are exceptions !! When I first came into contact with JavaScript, I thought this was a bit unpredictable and unpredictable.

If you feel the same way, you can read the following article:

  • Javascript this keyword Usage Analysis
  • [Illustration] JavaScript-"this" that you don't know"

This is usually used when binding events.

document.getElementById("input1").onclick = function(e){
this.style.color="Red";
};

  

2.2 event object

After debugging the following code, we can see that the event object usually contains the current key code and other event-related information. It is worth mentioning that the implementation of IE puts the event object in a global variable window. Event variable for storage, while other browsers that comply with W3C standards are passed as a parameter to the processing function.

 

Iii. Event binding

Although different browsers support different methods, compared with chaotic CSS, event binding still has rules to follow. IE has its own implementation method, and each version is unified. Other modern browsers are implemented according to W3C standards.

3.1 Traditional Dom binding

This method is the simplest and most effective. This keyword also points to the current element. But there are also many disadvantages. They are:

1. bind only once. If we bind the window. onload event in multiple referenced class libraries, the binding of the front edge will be overwritten by the back end and is often hard to detect.

2. Only events in the bubble phase can be subscribed.

3. The event parameter only supports non-ie. Although the event object parameter only supports non-ie browsers, we can solve this problem using the following method.

<a onclick="handle(event)" href="#">link</a>
3.2 W3C standard binding

This is the happiest way. modern browsers except ie support this. We can directly use addeventlistener (eventname, handlefunc, trueorfalse) of each Dom element ), the first parameter is the name of the subscribed event, such as click (no on), the second parameter is the time processing function, and the third parameter is whether to subscribe to the event capture stage.

The following is an example of using addeventlistener.

document.getElementById("linkA").addEventListener('click', function (e) {
alert('i am clicked!');
return stopDetault(e);
}, false);

Advantages:

1. Supports the bubble and capture phases.

2. Inside the processing function, this keyword references the current element.

3. Multiple processing functions can be bound to the same element at the same time without overwriting.

Disadvantages:

1. Internet Explorer does not support

3.3 ie binding

Since IE does not support addeventlistener, you must find a solution to help IE, that is, attachevent. Although there are many disadvantages, It is enough.

The following is an example of attachevent.

document.attachEvent("onload", function () {
alert("i am load");
});

  

Advantages:

1. Of course, this advantage is that, compared with the first binding method, the same element supports multiple binding times.

Disadvantages:

1. Only the bubble stage of IE events is supported.

2. The this keyword in the event processing function references the window object. To solve this problem, proceed to the next step.

3. You must add on before the event name. Of course, this is just a different name, and it does not matter.

4. Only Internet Explorer is supported. This is a pain point.

4. Niu Ren's solution Dean Edwards: addevent/removeevent Library

This solution is special. For details, see here

Features:
1 it performs no object detection
2 it does not use the addeventListener/attachEvent methods
3 it keeps the correct scope (the this keyword)
4 it passes the event object correctly
5 it is entirely cross-browser (it will probably work on IE4 and NS4)
6 and from what I can tell it does not leak memory

  

Source code:

function handleEvent(event) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fixEvent(window.event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};

function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
};

  

[Note]: This solution has a fatal issue. Do not overwrite the previously bound handler.

<body onload="alert('hi');"></body>

  

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.