JavaScript Basics Tutorial (i)-handling events

Source: Internet
Author: User
Tags event listener

I. Handling events (i)

Events ( Event ) is the action that the user performs when the page is accessed. Submitting the form and moving the mouse over the image are two events. When a browser detects an event, such as a mouse click or keystroke, it can trigger the JavaScript object associated with the event, which is called the event handler ( EventHandler) or a listener. .

1. Set HTML tag properties as event handlers (avoid use)

( 1 ) to directly JS code written in HTML on

<p onclick= "alert (' click ')" >html event handlers </p>

( 2 ) defines a function that assigns a value to the HTML Elements of OnXXX Properties

<type= "Text/javascript">    function  alert () {}; </ Script > <  onclick= "alert ()">HTML event handler </Div  >

Exposes many problems with the HTML event handler:

(1) The HTML code is tightly coupled to the JavaScript code, and if you want to replace the event handler, you need to change two places: HTML code and JavaScript code.

(2) The scope chain of an extended event handler can cause different results in different browsers. (not understood at the moment, can refer to the article SJ9009: The special scope chain of an inline event handler for an element differs in each browser

(3) There is a time difference problem . If stored in the function, then, there will be a problem-when the function is not defined (then the event handler may not have the execution conditions, the event handler may be in the JS script, has not been resolved), just HTML, CSS code loaded, the user clicks, will not respond completely. For this reason, many HTML event handlers are encapsulated in a try-catch block so that the error does not surface, as shown in the following example:

<type= "button"  value= "click me"  onclick= "try{ ShowMessage ();} catch (ex) {} "/>

(4) If you write more than one onclick event processing attribute to the same element, the browser executes only the code inside the first onclick, and the latter is ignored;

2. DOM0 -level event handlers ( all browsers support DOM0-level event handlers.) )

You can set the DOM property directly to specify the handler for an event

For example:

<DivID= "D3">Div3 Element</Div><Scripttype= "Text/javascript">    //Get Object    varD3=document.getElementById ('D3'); //Click eventsD3.onclick= function() {alert ("clicked"); }</Script>

is element the event that listens for nodes click .

The event handlers are not specified until the code is run, so if the code is behind a button in the page, there is a chance that there will be no response to the click in a period of time. (The code is not loaded yet). (I can't find D3 in front of it)

An event handler that is specified by using the DOM0-level method is considered a method of the element.

Btn.onclick=null;  To delete an event handler

set the event handler to NULL after that, clicking the button again will not have any action to occur.

Disadvantages
1. If the code is behind a button, it is possible that there is no response to a click in a period of time.
2. When the same object uses the . onclick notation to trigger multiple methods, the latter method overwrites the previous method. that is, when an object's OnClick event occurs, only the last bound method is executed. Instead, the event listener will not overwrite, and each bound event will be executed. But the IE Family First executes the post-bind method, which is the inverse binding order execution method, and the other browsers execute the method in the order of the binding number.

3. DOM2 Level Event handlers
The "DOM2 level event" defines two methods for handling the actions of the specified and deleted event handlers: AddEventListener () and RemoveEventListener ()
1) AddEventListener

Element.addeventlistener (<event-name><callback>  <use-capture>);

Parameter one: Event-name event name or type
Parameter two: Callback callback function, will be called when the event is triggered.
Parameter three: Use-capture indicates whether the event listener listens (set to True) in the capture phase or listens (set to false) in the bubbling phase.

Cases

<id= "btn"> Click here </button>var BTN = document.getElementsByTagName (' button '), Btn.addeventlistener (' click ', Function () {    alert (' You clicked this button ');}, FALSE);

2) RemoveEventListener

If we want to unbind, we need to use the RemoveEventListener method:

Element.removeeventlistener (<event-name><callback  ><use-capture>);

It is important to note that the callback function when binding an event cannot be an anonymous function, it must be a declared function, because a reference to the callback function needs to be passed when the event is unbound to break the binding. For example:

var fun = function () {    //function Logic};element.addeventlistener (' Click ', fun, false); Element.removeeventlistener (' Click ', fun, false);
Characteristics:

1) The event handler is bound to the element only after running AddEventListener () .
2) You can bind multiple event handlers for the same element, register multiple events of the same type with the same object through the AddEventListener () method, do not ignore or overwrite them, but execute sequentially in order ; This is not supported by the DOM0 level event handlers. Only one event handler can be added at the DOM0 level , and later additions will overwrite the first .
3) Event handlers added using Addeventlister () can only be removed using Removeeventlister (). And keep the parameters the same.
4)IE9, Firefox, Safari, Chrome and opera all support DOM2-level event handlers, and the AddEventListener () method does not support IE9 (not including IE9) below 's browser.

4. IE Event Handling Program

IE8 and its previous versions of the browser do not support AddEventListener () and RemoveEventListener (). However, IE defines a similar approach to attachevent () and DetachEvent ().
Attachevent () and detachevent () require only two parameters: the event type and the event handler function.
Note: IE10 and previous versions support the Attachevent () and DetachEvent () methods, IE11 no longer support, and generally IE9 and above use DOM methods, both of which are used only for IE8 and the following versions. Only IE and opera support IE event handling

To add an event handler:

var btn = document.getElementById (' mybtn '); btn.attachevent (function//  Note that this is the onclick ~    console.log (' hello ');});
To remove an event handler:

Using detachEvent The Remove event handler is the same condition as the DOM method-- you must provide the same parameters so that the added anonymous function cannot be removed.

var btn = document.getElementById (' mybtn '); Btn.detachevent (' onclick ', show);

Characteristics:

1) attachEvent() The event handler is bound to the element only after it has run.
2) Multiple event handlers can be bound for the same element, and the bound event handlers are triggered in the order in which they are added, that is, after they are added and executed first.

Note: This article is original, reproduced please link to the form marked this article address, thank you for your cooperation.

This address: http://www.cnblogs.com/wanghuih/p/5611682.html

JavaScript Basics Tutorial (i)-handling events

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.