Js Event Details (1) event types and several methods to add event handlers __js

Source: Internet
Author: User

Events in JS

Two solutions to an earlier event flow:

1.IE: Event bubbling Flow
That is, the event is initially received by the most specific element (the deepest node in the DOM) and then propagated up to the less specific node (document)-from the bottom up.

Event bubbling is supported by all modern browsers.

2.Netscape Communicator: Event capture Stream.
The event bubbling stream is just the opposite of what the IE team is proposing. Propagated by less specific nodes to specific nodes.

The purpose of doing so is to capture the event before it reaches a predetermined target.

The current mainstream browsers support the event flow model, but older browsers may not support it.

So be sure to use the event bubbling model with confidence.

one, DOM event flow

The "DOM2 level event" sets the three stages of an event flow:

1. Event Capture Phase
2. Process Target Phase
3. Event bubbling Phase

"Figure 13-3"

The three phases are performed sequentially, typically responding to events during the bubbling phase of the event.

Attention:

1. Although the "DOM2 event" specification explicitly requires that the capture phase not involve event targets, mainstream browsers trigger events on event objects during the event capture phase. As a result, there are 2 opportunities to manipulate events above the target object.
Dom event flow is not supported before 2.IE8.

Ii. Event Handlers

Plainly, is the function that responds to events. Generally with ' on ' start, such as onload, OnClick and so on.

Several ways to add the focus of an event handler:

1.HTML Event Handlers

Each event supported by a DOM element can be specified with an HTML attribute that has the same name as the corresponding event handler.

Such as:

Or:

<script type= "Text/javascript" > 
    function ShowMessage () { 
        alert ("Hello world!"); 
    } 
</script> 

This specifies the event handler, which creates a function that encapsulates the element's attribute value (this in the function represents the current DOM element in the), and there is a local variable event, which is the event object.

<input type= "button" value= "click Me" onclick= "alert (event.type)" >
<input type= "button" value= "click Me" onclick= "alert (this.value)" >

What's more interesting about this dynamically created function is how it expands the scope, and it does this:

function () {
    with (document) {
        and (this) {
            //Element property value

        }
}}

By doing so, it makes it much simpler to access the element's own properties.

When the element is a form element, the scope also includes an entry to access the form element (the parent element of the current element):

function () {with
    (document) {with (This.form) {with (this
            ) {
                //element property
            }
}}
<form method= "POST" > 
    <input type= "text" name= "username" value= "" > 
    <input type= "button" value= "Echo Username" onclick= "alert (username.value)" > 
</form>

This expands the scope in such a way that an event handler can access other form fields without having to refer to the form element.

The disadvantage of this method of adding event handling:

<1> There is time difference:
If the event handler function is written below the element, the element may be parsed first, and the corresponding function of the event handler has not been loaded, at which point the response to the event will be wrong.

<2> This extends the scope of the event handlers differently in different browsers.

<3>. The HTML code is tightly coupled to the JS code.

2.dom0-level event handlers

Each element (including window and document) has its own event handler properties, which are usually all lowercase, such as onclick.

var btn = document.getElementById (' mybtn ');
Btn.onclick = function () {
    alert (this.id);
}

The event handler specified using the DOM0 level event is considered a method of the element, so this in the event handler refers to the current element, which can be accessed through other properties of the element. That is, the event runs in the scope of the current element.

To delete an event handler:

Btn.onclick = null;

3.dom2-level event handlers

AddEventListener ()
RemoveEventListener ()

The two functions accept three parameters: the event name, the event handler function, the Boolean value (True indicates that the event invokes the event handler in the capture phase, false, which indicates that the event handler is invoked during the bubbling phase)

var btn = document.getElementById (' mybtn ');
Btn.addeventlistener (' click ', Function () {
    alert (this.id);//this still represents the element},false of the current triggering event
);

You can add multiple event handlers for an element, and the events respond in the order in which the event handlers are added.

RemoveEventListener (): Removes the event, the second argument must be the second parameter of the AddEventListener (), which means that the event handler function cannot be an anonymous function, otherwise it cannot be removed.

With respect to the third parameter, it is strongly recommended that you set it to false, which is to handle events in the bubbling phase to maximize compatibility with the large browsers.

4.IE Event Handlers

provides two methods for adding and removing event handlers:

Attachevent ()
detachevent ()

The first parameter is the event handler name ("on" + event name) and the second parameter is the event handler.

var btn = document.getElementById (' mybtn ');
Btn.attachevent (' onclick ', function () {
    alert (' click ');
});

Attention:
Unlike the DOM0 level event and the DOM2 level event, the handler for the IE event is not running in the scope of the element, but is running in the global scope. This is the window object represented by this in the event handler specified by IE.

You can add multiple event handlers for an element, but the order of execution is performed backwards, that is, the last event handler that you add is first executed.

To remove an event handler:
DetachEvent ()
An anonymous event handler cannot be removed.

5. Cross-browser event handlers

is to detect the types of events supported by each browser. The DOM0 level method is used by default.

var eventutil = {

    addhandler:function (element, type, handler) {
        if (Element.addeventlistener) {// Determine whether to support DOM2 level event handling
            Element.addeventlistener (type,handler,false);
        } else if (element.attachevent) {
            element.attachevent (' on ' +type,handler);
        } else{
            element[' on ' +type] = handler;//By default DOM0-level method.
        }
    ,

    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;
        }
    }
;

Attention:
<1> here is a simple consideration of adding and removing event handlers for elements, and does not consider other issues, such as event handlers running scopes.
The <2>dom level event only supports adding an event handler, that is, you have repeatedly called this method to add multiple event handlers to the element, and the result is that only the last one is added. However, now only support DOM0 browser seems to be not much, so generally do not go to the last else.

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.