JS Event binding, Event monitoring, Event delegation details

Source: Internet
Author: User

Event Bindings

To allow JavaScript to respond to a user's actions, first bind the event handler to the DOM Element. The so-called event handler function is the function that handles the user operation, and different operations correspond to different names.

In javascript, there are three common ways to bind events:

    1. Bind directly in the DOM element;
    2. Binding in JavaScript code;
    3. Binds the event listener Function.

To bind an event directly in the DOM

We can bind the onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeypress, onkeyup, etc. on the DOM Element. A lot is not listed. If you want to know more about the event types, see Dom Events.

<input type= "button" value= "click me" onclick= "hello ()" > <script>function Hello () {alert ("hello world!");} </script>

Binding events in JavaScript code

Binding events in JavaScript code (that is, in a script Tag) separates JavaScript code from HTML tags, makes the document structurally clear and easy to manage and develop.

<input type= "button" value= "click me" id= "btn" > <script>document.getelementbyid ("btn"). onclick = function () {alert ("hello world!");} </script>

Using events to listen for bound events

Another way to bind an event is to use AddEventListener () or attachevent () to bind the event listener Function. The following details, event Monitoring.

Event Monitoring

About event monitoring, The 3 event stages are defined in the code, which is the capturing phase, the target stage and the bubbling Stage.

At first Netscape developed a set of JavaScript Event-driven mechanisms (I.E. event captures). IE also launched its own set of Event-driven mechanisms (that is, event bubbling). finally, We standardize two kinds of event mechanism, which are divided into capturing stage, target stage and bubbling stage. IE8 before IE has insisted on its own event mechanism (front-end staff has been headache compatibility problem), IE9 after IE also support the Specifications.

Specifications

Grammar:

Element.addeventlistener (event, function, Usecapture)

Event: (required) Events name that supports all Dom Events.

Function: (required) Specifies the functions to execute when the event is Triggered.

Usecapture: (optional) Specifies whether the event is executed during the capture or bubbling phase. True to Capture. false, Bubbling. False by Default.

Note: IE8 below are not supported.

<input type= "button" value= "click me" id= "btn1" > <script>document.getelementbyid ("btn1"). AddEventListener ("click", hello); function Hello () {alert ("hello world!");} </script>

IE standard

Grammar:

Element.attachevent (event, Function)

Event: (required) Type. Need to be "on", for example: onclick.

Function: (required) Specifies the functions to execute when the event is Triggered.

<input type= "button" value= "click me" id= "btn2" > <script>document.getelementbyid ("btn2"). attachevent (" OnClick ", hello); function Hello () {alert (" Hello world! ");} </script>

Benefits of event Monitoring

1. Multiple events can be bound.

<input type= "button" value= "click me" id= "btn3" > <script>var btn3 = document.getElementById ("btn3"); Btn3.onclick = function () {alert ("hello 1");//do Not execute}btn3.onclick = function () {alert ("hello 2");//execute}</script>

The regular event binding only executes the last bound Event.

<input type= "button" value= "click me" id= "btn4" > <script>var btn4 = document.getElementById ("btn4"); Btn4.addeventlistener ("click", hello1); Btn4.addeventlistener ("click", hello2); function Hello1 () {alert ("hello 1");} function Hello2 () {alert ("hello 2");} </script>

Two events have been Executed.

2, you can remove the corresponding binding

<input type= "button" value= "click me" id= "btn5" > <script>var btn5 = document.getElementById ("btn5"); Btn5.addeventlistener ("click", hello1);//executed btn5.addeventlistener ("click", hello2);//do not execute Btn5.removeeventlistener ("click", hello2); function Hello1 () {alert ("hello 1");} function Hello2 () {alert ("hello 2");} </script>

Encapsulating event Monitoring

<input type= "button" value= "click me" id= "btn5" >//binding Listener event function addEventHandler (target,type,fn) {if ( Target.addeventlistener) {target.addeventlistener (type,fn);} Else{target.attachevent ("on" +type,fn);}} Remove Listener event function removeEventHandler (target,type,fn) {if (target.removeeventlistener) {target.removeeventlistener ( type,fn); }else{target.detachevent ("on" +type,fn);}} Test var btn5 = document.getElementById ("btn5"), addeventhandler (btn5, "click", hello1);//add Event Hello1addeventhandler ( btn5, "click", Hello2);//add Event hello2removeeventhandler (btn5, "click", hello1);//remove Event Hello1

Event delegate

Event delegation is the use of the principle of bubbling, the event is added to the parent or ancestor elements, triggering the effect of Execution.

<input type= "button" value= "click me" id= "btn6" > var btn6 = document.getElementById ("btn6");d Ocument.onclick = function (event) {event = Event | | window.event; var target = Event.target | | event.srcelement; if (target = = Btn6) {alert (b tn5.value); }

Above is just an example, the code is as simplified as Possible. In the actual code we may use Jquery's Live (), delegate (), bind (), on (), and so On.

Event Delegation Advantages

1. Improve JavaScript Performance. Event delegates can significantly increase the processing speed of events and reduce the memory Footprint. The example parses event delegates and event bindings in javascript, and this article is well Written.

Traditional notation

<ul id= "list" > <li id= "item1" >item1</li> <li id= "item2" >item2</li> <li id= "item3" >item3</li></ul> <script>var item1 = document.getElementById ("item1"); var item2 = document.getElementById ("item2"), var item3 = document.getElementById ("item3"); Item1.onclick = function () {alert ("hello item1");} Item2.onclick = function () {alert ("hello item2");} Item3.onclick = function () {alert ("hello item3");} </script>

  

Event delegate

<ul id= "list" > <li id= "item1" >item1</li> <li id= "item2" >item2</li> <li id= "item3" >item3</li></ul> <script>var item1 = document.getElementById ("item1"); var item2 = document.getElementById ("item2"), var item3 = document.getElementById ("item3"); Document.addeventlistener ("click", function (event) {var target = event.target; if (target = = Item1) {alert ("hello Item1") ; }else if (target = = Item2) {alert ("hello item2");} else if (target = = Item3) {alert ("hello Item3");}}) </script>

  

2. Dynamic addition of DOM elements, do not need to modify the event binding because of element changes.

Traditional notation

<ul id= "list" > <li id= "item1" >item1</li> <li id= "item2" >item2</li> <li id= "item3" >item3</li></ul> <script>var list = document.getElementById ("list"); var item = List.getelementsbytagname ("li"); for (var i=0;i<item.length;i++) {(function (i) {item[i].onclick = function () {alert (item[i].innerhtml);}}) (i)} var node=document.createelement ("li"), var textnode=document.createtextnode ("item4"); Node.appendchild ( textnode); List.appendchild (node); </script>

  

Click Item1 to Item3 there are event responses, but when you click item4, there is no incident response. Description Traditional event bindings cannot dynamically add events to dynamically added Elements.

Event delegate

<ul id= "list" > <li id= "item1" >item1</li> <li id= "item2" >item2</li> <li id= "item3" >item3</li></ul> <script>var list = document.getElementById ("list"); Document.addeventlistener ("click", function (event) {var target = event.target; if (target.nodename = = "LI") {alert ( target.innerhtml); }}) var node=document.createelement ("li"), var textnode=document.createtextnode ("item4"); node.appendchild (textnode ); List.appendchild (node); </script>

  

When you click item4, item4 has an event response. Description event delegates can add events dynamically for newly added Dom Elements.

Original Link: http://www.open-open.com/lib/view/open1475031370328.html

JS Event binding, Event monitoring, Event delegation details

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.