JS event Learning notes (1). js event Learning notes

Source: Internet
Author: User

JS event Learning notes (1). js event Learning notes
1. event stream

If an element has an ancestor Element and Its ancestor element defines the same event as it, when an event occurs on the element, it involves the sequence of events transmitted between the element and the ancestor element.
There are two types:
Event bubbling: Receives the event from the most specific element, executes the event handler, and passes the event up to the document Object.
If an event is triggered on an element, its event handler is called. If the element does not define an event handler or the event returns true, the event is processed by the parent object, from the inside out, all similar events of the parent object will be activated. Until the document Object is uploaded.
Event capture: On the contrary, capture the document from the outermost layer and then pass it to the most specific element in sequence. That is, after an event is triggered in an internal element, the event is intercepted by an external element and the event processing program bound to it is executed. Then, the event is passed down to the internal element.
Generally, event bubbles are used.

DOM2-level event stream

There are three phases: capture phase, in the target phase (events are received by the actual target), and event bubbling phase (in this phase, let the specific target respond to the event ). That is to say, the event is first passed down from the document to the target object, and then passed to the document in blister mode. However, the specific stage in which the element executes the event handler is set by the parameters of the function that adds the event. That is to say, the parent element must receive the event first, but it may not be executed when it is intercepted.
Most browsers that support dom Event streams follow the rules: events are not involved in the capture phase, but chrome, Firefox, IE9, and other browsers can trigger events on Event objects in the capture phase, the result is that there are two opportunities (stages) to operate events on the target object.

2. event handler A. html event handler

That is, the function corresponding to an event, starting with "on. The code in the event handler has the right to access any code in the global scope during execution.
The function has a local variable even that does not need to be customized, that is, the event object. this in the function points to the target element of the event.
Extended scope: with statement
Disadvantage p-350 of this method

B. JavaScript specifies the event handler

1. DOM0-level event handler

This method tightly coupled JavaScript code and html. Use JavaScript to specify the event handler: Assign the function to the event handler attribute of the object to be operated. For example, btn. onclick = function (){}.
Note: No event handler is specified before JS Code runs to bind an event. Therefore, if the code is located behind the button in the page, it may not respond if you click the button within a period of time.
The event handler specified in this method is considered an element method and runs in the element scope. this references the current element.This method is specified and will be processed in the event stream bubble stage. DOM0 supports only one event handler for the same event on a DOM element, and the latter will overwrite the previous event handler (you can bind different events to a DOM element ).
Delete Bound event: btn. onclick = null

2. DOM2-level event handler
The Methods addEventListener () and removeEventListener () are defined for DOM nodes to set and delete Event Handlers. Both methods contain three parameters:

  • Parameter 1: Specify the event name
  • Parameter 2: Specify the event handler
  • Parameter 3: Boolean value. "true" indicates that the object receiving the event calls the event processing program in the event capture phase. "false" indicates that the object receiving the event will not be called until it is in the bubble phase. For example:
// Html code <div id = "outside"> I am outside <div id = "inside"> I am inside </div> // js code window. onload = function () {var outside = document. getElementById ("outside"); outside. addEventListener ("click", function () {alert ("I am outside")}, true); // call var inside = document in the capture phase. getElementById ("inside"); inside. addEventListener ("click", function () {alert ("I am inside")}, true );}

In the code above, the event handler of the outside box is set to true. If the event is intercepted during the capture phase, the event handler is called immediately, that is to say, if an internal box is clicked, the output order is "I am outside" and "I am inside".
If the external box is set to "true" to "false", it means that the processing program is called only in the bubble stage. After you click the internal box, the output sequence is "I am inside", "I am outside ".

This method is still carried out in the scope of the attached element. This method has the following advantages:Multiple events can be added (including events with the same name that are not overwritten) and executed in the order of addition.
Note:: The removeEventListener () parameter is the same as that of addEventListener, but the anonymous function cannot be removed. That is to say, the event is not unbound and is still effective.In fact, this function is totally different from the anonymous function passed in addEventListener. It can be solved by passing in the variables that hold the reference of the anonymous function:
In IE, only IE9 supports the DOM2 method.

<script type="text/javascript">window.onload=function(){    var btn = document.getElementById("show");    var handler = function(){alert(this.value)};    btn.addEventListener("click",handler,false);    btn.removeEventListener("click",handler,false);}</script>

To maximize compatibility with various browsers, it is best to add the event handler to the bubble stage of the event stream, you only need to add the event handler to the capture phase when the event is intercepted before it reaches the target.

3. IE event handler

IE implements two methods: attachEvent () and detachEvent (),The added event handler is added to the bubble stage.. What is the difference between it and DOM0 and DOM2?The scope of the event handler is not the element to which it belongs (this = The element bound to the event), but global, that is, this = window. You can also add multiple events to an element, but the execution sequence is the first execution after the element is added. DetachEvent is used to cancel an event. Similarly, anonymous function parameters cannot be removed and should be passed for reference.
The execution sequence of functions processed by IE8 and below is the opposite to the binding order, while that of other IE browsers is normal.

<Script type = "text/javascript"> window. onload = function () {var out = document. getElementById ("outside"); out. attachEvent ("onclick", function () {alert ("I am outside")}); // note that "onclick" is used instead of "click" var inside = document. getElementById ("inside"); inside. attachEvent ("onclick", function () {alert ("I am inside")}) ;}</script>

4. cross-browser event handler

Var EventUtil = {addHandler: function (element, type, handler) {if (element. addEventListener) {// DOM2-level method element. addEventListener (type, handler, false);} else if (element. attachEvent) {// IE Method element. attachEvent ("on" + type, handler);} else {// DOM0 level element ["on" + type] = handler ;}}, removeHandler: function (element, type, handler) {if (element. removeEventListener) {element. removeEventListener (type, handler, false);} else if (element. detachEvent) {element. detachEvent ("on" + type, handler);} else {element ["on" + type] = null ;}}};
3. Event bubbling prohibited

Let's talk about several related methods and attributes:

  • CancelBubble (attribute of the html dom Event object): If the Event handle wants to prevent the Event from spreading to an inclusive object, it must be set to true.
  • StopPropagation (html dom Event object method): terminates the further propagation of an Event during the capture, target processing, or blister phase of the propagation process. After this method is called, the handler for processing the event on the node will be called, and the event will not be assigned to other nodes.

You can write programs that prevent event bubbling into the following functions:

function stopBubble(e){    if(e && e.stopPropagation){        e.stopPropagation(); //DOM    }else{        window.even.cancelBubble=true; //IE    }}

Put this stopBubble (e) function in the function that you want to block event bubbling to prevent event bubbling.

Four event objects

1. DOM Event object

In modern browsers, an event object is input as a parameter for the event handler. When ie binds an event in the DOM0-level mode, the event is the property of the window object, the other method is the parameter of the event processing function.
Different events have different attributes and methods, but in modern browsers, all event objects have the following attributes and methods:

  • CurrentTarget attribute: the element that the event handler is processing (that is, the element that is calling the event handler). this is always equal to currentTarget. The target attribute points to the most specific target, that is, the element that actually triggers the event.
<Script type = "text/javascript"> var outside = document. getElementById ("outside"); var inside = document. getElementById ("inside"); outside. onclick = function (event) {// pass the event parameter alert ("I am outside"); alert ("this = event. currentTarget? "+ (This = event. currentTarget); // + priority over === alert (" event.tar get = this? "+ (Event.tar get = this); alert (" event.tar get = inside? "+ (Event.tar get = inside);}; inside. onclick = function (event) {alert ("I am inside"); alert ("this = event. currentTarget? "+ (This = event. currentTarget); alert (" event.tar get = this? "+ (Event.tar get = this); alert (" event.tar get = inside? "+ (Event.tar get === inside) ;}; </script>
  • Type attribute: Event type
  • PreventDefault (): prevents the default action when an event is triggered. For example, you can click a hyperlink to go to the page specified by the url. This method can be used only for events whose cancelable attribute is set to true.
  • EventPhase attribute: the stage in which the event handler is called. 1 indicates the capture phase, 2 indicates the target object, and 3 indicates the bubble phase.

The event object exists only when the event processing program is running. After running, it is destroyed.

2. Event objects in IE

There are several methods for event objects in IE, depending on the method for adding events. If the DOM0-level method is used, the event object, as an attribute of the window object, should be used in the form of window. event. If the attachEvent () method is used, event is used as the parameter of the event processing function, and can also be used as the window attribute.
This object includes the following attributes and methods:
-CancelBubble attribute: The default value is false. If it is set to true, the event bubble is canceled.
-ReturnValue property: the default value is true. If it is set to false, the default behavior when the event is triggered is canceled.
-SrcElement property: Same as target

Note: (1) in IE, the scope of the event handler is determined by the method of adding it. If the DOM0 level method is used, this is the element that calls the handler, this = window. Therefore, it cannot be considered that this will always be equal to the event Target. Use event. srcElement to specify the event target to be more secure.
(2) IE does not support event capture. You can only cancel event bubbling by using cancelBubble, while stopPropagation () can cancel both capture and bubble.

3. cross-browser event objects

The event objects in DOM and IE are different, but they have many methods and attributes that correspond to each other. The EventUtil object is enhanced here to implement cross-browser event objects and event handlers.

<Script type = "text/javascript"> var EventUtil = {addHandler: function (element, type, handler) {if (element. addEventListener) {// DOM2-level method element. addEventListener (type, handler, false);} else if (element. attachEvent) {// IE Method element. attachEvent ("on" + type, handler);} else {// DOM0 level element ["on" + type] = handler ;}}, removeHandler: function (element, type, handler) {if (element. removeEventListener) {element. removeEventL Istener (type, handler, false);} else if (element. detachEvent) {element. detachEvent ("on" + type, handler);} else {element ["on" + type] = null ;}, getEvent: function (event) {// no matter how the event parameter is passed in, if DOM0 is implemented in IE, the event is the return event of undefined? Event: window. event;}, getTarget: function (event) {return event.tar get | event. srcElement;}, preventDefault: function (event) {if (event. preventDefault) {event. preventDefault ();} else {event. returnValue = false ;}}, stopPropagation: function (event) {if (event. stopPropagation) {event. stopPropagation ();} else {event. cancelBubble = true ;}}; </script>

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.