JS Event Program Processing

Source: Internet
Author: User

First, the basic concept

1. Event: The user/browser performs some kind of action (click, Load Load, page scrolling scroll, etc.);
2. Event handler: A handler function that responds to an event, also known as an event listener

Ii. Event Flow Event flow
1、事件冒泡    由IE提出    由下向上2、事件捕获    由Netscape团队提出    由上向下    由于老版本浏览器不支持,所以很少使用3、DOM事件流    DOM2级事件    分为三个阶段:事件捕获阶段、处于目标阶段、事件冒泡阶段     IE8及更早版本不支持,目前最常用的事件流    
Third, how to bind event handler function event: Events Object this: point to Event Target (i), HTML bindings
<li onclick="alert(this)">1行</li>
(b), JS binding

Three different ways

Mode one DOM0 level method
var ele = document.getElementsByTagName(‘li‘)[0];// 绑定ele.onclick = function (event) {    console.log(event);};// 同时给一个元素相同事件绑定两个事件处理函数时,后面的代码会覆盖前面的ele.onclick = function (event) {    console.log(this);};// 解绑ele.onclick = null;

This method cannot bind multiple events at the same time

Mode two DOM2 level method

AddEventListener and RemoveEventListener

function handler1(event) {        console.log(this);}function handler2(event) {    console.log(event);}// 三个参数          1.一个/多个事件 2.事件处理函数 3.响应阶段(捕获阶段:true, 冒泡阶段:false 一般使用false)ele.addEventListener(‘click‘, handler1, false);// 同时为同一个元素的同一个事件绑定多个处理函数时,不会覆盖,会按照绑定顺序执行ele.addEventListener(‘click‘, handler2, false);// 解绑 三个参数必须和绑定时保持一致才可以解绑ele.removeEventListener(‘click‘, handler1, false);
Note: 1, the parameters of the binding function must be consistent with the binding parameters to be able to unbind; 2, so it is best not to use anonymous functions, otherwise the solution is not tied; 3. When you bind multiple handlers for the same event of the same element, they are not overwritten and are executed in the binding order. Way three IE (IE8 previously only supported this bubbling mode)

Attachevent and DetachEvent

// 绑定 两个参数 1.on‘事件‘ 2.事件处理函数ele.attachEvent(‘onclick‘, handler1);ele.attachEvent(‘onclick‘, handler2);// 解绑ele.detachEvent(‘onclick‘, handler1);
Note: 1, the parameters of the binding function must be consistent with the binding parameters to be able to unbind; 2, so it is best not to use anonymous functions, otherwise the solution is not tied; 3. When you bind multiple handlers for the same event for the same element, they are not overwritten and are executed in the reverse order of binding. 4. This does not specify the event target but points to the Window,event object and the first two event compositions are not the same. Four, compatible with IE8 and the following browser event binders
var handler = function (event) {Console.log (' Events type: ' +event.type+ ' event stage: ' +event.eventphase ');} Package compatible Event Binder var eventutil = {//bind event handler addhandler:function (element, type, handler) {if (Element.addeven        Tlistener) {Element.addeventlistener (type, handler, false);        } else if (element.attachevent) {element.attachevent (' on ' +type, handler);        } else {element[' on ' +type] = handler;            }},//Unbind processing 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;    }},//Get Event Object Getevent:function (event) {return event? event:window.event;    },//Get event Target Element Gettarget:function (event) {return Event.target | | event.srcelement; },//block the default behavior of specific events PREventdefault:function (Event) {if (Event.preventdefault) {event.preventdefault ();        } else {event.returnvalue = false; }},//block bubbling Stoppropagation:function (event) {if (event.stoppropagation) {Event.stoppropagat        Ion ();        } else {event.canclebubble = true; }}};//calls Eventutil.addhandler (Ele, ' click ', handler); Eventutil.removehandler (ele, ' click ', handler);
V. Event object
Event Mainstream Browser Event IE8 below window.event
The element that the event handler is working on Event.currenttarget
The specific element in which the event occurred Event.target Event.srcelement
Block default behavior for specific events Event.preventdefault () Event.returnvalue = False
Block event bubbling Event.stoppropagation () Event.canclebubble = True

Event.eventphase the stage at which an element is in when the event handler function is judged
1: During the capture phase
2: On the target object
3: Bubbling Stage

Event.eventphase = 2 o'clock, This=event.currenttarget = Event.target

Six, the event entrusted to solve the problem: if all the elements of the page need to bind the event handler, 1, then will be bound a lot of separate programs, global memory consumption, affect page performance, 2, access Dom too many times, delay page interaction Readiness Time principle: using event bubbling, Specify event handlers for top-level page elements or for the head element in a module

Html:

<div id="box">    <ul id="list">        <li id="one">1行</li>        <li id="two">2行</li>        <li id="three">3行</li>    </ul></div>

Js:

var ele = document.getElementById(‘box‘);EventUtil.addHandler(ele, ‘click‘, function (event) {    var event = EventUtil.getEvent(event);    // 获取发生事件的目标元素    var target = EventUtil.getTarget(event);    // 获取事件目标元素的id选择器名    var id = target.id;    // 根据不同的元素做不同的处理    switch(id) {        case ‘box‘:        {            handler(event);        }            break;        case ‘list‘:        {            console.log(target);        }            break;        case ‘one‘:        {            target.style.color = ‘red‘;        }            break;        case ‘two‘:        {            target.style.color = ‘blue‘;        }            break;        case ‘three‘:        {            target.style.color = ‘green‘;        }            break;        default: break;    }});

JS Event Program Processing

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.