JavaScript event binding and in-depth _ basic knowledge-js tutorial

Source: Internet
Author: User
This article describes how to bind and deepen JavaScript events. You can refer to the following two types of event binding:

One is traditional event binding (Inline model/script model); the content of the previous chapter;
One is modern event binding (DOM2-level model); modern event binding provides more powerful functions based on traditional event binding;
A traditional event binding Problem

// The Script model assigns a function to an event handler; var box = document. getElementById ('box'); // get the element; box. onclick = function () {// trigger event of element click; alert ('lil');} // Question 1: one event processing function triggers two events; window. onload = function () {// The first program; alert ('lil');} window. onload = function () {// The second program; alert ('Mr. lee ');} // PS: when the two groups of programs are executed simultaneously, the latter will completely overwrite the previous one; // cause the previous window. onload is completely invalid; // solution: window. onload = function () {// the first group of Event Handlers will be overwritten; alert ('lil');} if (typeof window. onload = 'function') {// determines whether a window exists before. onload; var saved = null; // create a save; saved = window. onload; // set the previous window. onload to save;} window. onload = function () {// the next event to be executed; // saved () = window. onload = function if (saved) saved (); // determines whether an event exists. if yes, run the previously saved event first. alert ('Mr. lee '); // code for executing this event ;}

// Question 2: event switch box. onclick = boBlue; // the first execution of toBlue (); function toRed () {this. className = 'red'; this. onclick = toBlue; // perform roBlue () for the third time and switch back and forth.} function toBlue () {this. className = 'blue'; this. onclick = toRed; // The second execution of toRed ();} // when the switch is extended, some problems may occur: 1. if an execution function is added, it will be overwritten. box. onclick = toAlert; // added function; box. onclick = toBlue; // toAlert is overwritten; 2. if the overwriting problem is solved, it must be included and executed simultaneously; box. onclick = function () {// contains, but the readability is reduced; toAlert (); // it will not be overwritten for the first time, but will be overwritten for the second time; toBlue. call (this); // you must pass this to the switch ;}

// To sum up the three questions: overwrite question/readability question/this is passed as the question; // we create a custom event processing function; function addEvent (obj, type, fn) {// replace the traditional event processing function; var saved = null; // Save the event processing function triggered each time; if (typeof obj ['on' + type] = 'function') {// you can check whether an event exists. saved = obj ['on' + type]; // if yes, save it;} obj ['on' + type] = function () {// then run; if (saved) saved (); // execute the previous; fn. call (this); // execute the function and pass this in;} addEvent (window, 'load', function () {alert ('lil '); // executable;}); addEvent (window. 'load', function () {alert ('Mr. lee '); // executable;}) // use a Custom Event function to register it on the switch to view the effect: addEvent (window, 'load', function () {var box = document. getElementById ('box'); addEvent (box, 'click', toBlue) ;}); function toRed () {this. className = 'red'; addEvent (this, 'click', toBlue);} function toBlue () {this. className = 'blue'; addEvent (this, 'click', toRed );

2. W3C event processing functions
// "DOM2-level event" defines two methods for adding and deleting events: addEventListener () and removeEventListener ();

// All DOM nodes contain these two methods, and each of them receives three parameters: event name/function/Boolean value for bubble or capture (true indicates capture, false indicates bubble ); window. addEventListener ('load', function () {alert ('lil') ;}, false); window. addEventListener ('load', function () {alert ('Mr. lee ') ;}, false); // PS: W3C event binding benefits: 1. no need to customize; 2. the same functions can be shielded; 3. you can set bubble and capture; window. addEventListener ('load', init, false); // the first execution; window. addEventListener ('load', init, false); // blocked for the second time; function init () {alert ('lil');} // event switch window. addEventListener ('load', function () {var box = document. getElementById ('box'); box. addEventListener ('click', function () {// will not be overwritten/accidentally deleted; alert ('lil') ;}, false); box. addEventListener ('click', toBlue, false); // introduces switching;}, false); function toRed () {this. className = 'red'; this. removeEventListener ('click', toRed, false); // remove the event handler; this. addEventListener ('click', toBlue, false); // Add the event handler function to be switched;} function toBlue () {this. className = 'blue'; this. removeEventListener ('click', toBlue, false); this. addEventListener ('click', toRed, false);} // sets the document in the bubble and capture phases. addEventListener ('click', function () {alert ('document') ;}, true); // set to capture; document. addEventListener ('click', function () {alert ('lil') ;}, false); // set it to bubble;

3ie event processing functions
// Two methods similar to those in DOM are implemented in IE: attachEvent () and detachEvent ();

// These two methods receive the same parameter: event name and function;

// The difference between the two functions: // 1. IE does not support capture, only supports bubbling; // 2. duplicate functions cannot be blocked when adding events to IE; // 3. this in IE points to a window rather than a DOM object; // 4. in traditional events, IE cannot accept event objects, but attachEvent () can be used; window. attachEvent ('onload', function () {var box = document. getElementById ('box'); box. attachEvent ('onclick', toBlue) ;}); function toRed () {var that = window. event. srcElement; that. className = 'red'; that. detachEvent ('onclick', toRed); that. attachEvent ('onclick', toBlue);} function toBlue () {var that = window. event. srcElement; that. className = 'blue'; that. detachEvent ('onclick', toBlue); that. attachEvent ('onclick', toRed);} // PS: capture is not supported by IE; // IE cannot be blocked; // IE cannot pass this and can call the past; // In traditional binding, IE cannot accept event objects by passing parameters like W3C; but if attachEvent () is used, it can; box. onclick = function (evt) {alert (evt); // undefined;} box. attachEvent ('onclick', function (evt) {alert (evt); // object; alert (evt. type); // click;}); // compatible with the event switch functions of IE and W3C; function addEvent (obj, type, fn) {// compatible with adding event handlers; if (obj. addEventListener) {obj. addEventListener (type, fn);} else if (obj. attachEvent) {obj. attachEvent ('on' + type, fn) ;}} function removeEvent (obj, type, fn) {// compatible with the removal event handler; if (obj. removeEventListener) {obj. removeEventListener (type, fn);} esle if (obj. detachEvent) {obj. detachEvent ('on' + type, fn) ;}} function getTarget (evt) {// get the event Target; if(evt.tar get) {return evt.tar get;} else if (window. event. srcEleemnt) {return window. event. srcElement ;}}

Event object supplement

1. relatedTarget // This attribute can be used to obtain the DOM object from where to move and from in the mouseover and mouseout events; box. onmouseover = function (evt) {// move the mouse into the box; alert (evt. relatedTarget); // obtain the element before it is moved into the box;} box. onmouseout = function (evt) {// move the mouse out of the box; alert (evt. relatedTarget); // obtain the element from which the box is removed;} // IE provides two sets of corresponding attributes: fromElement and toElement; // compatible with function getEarget (evt) {var e = evt | window. event; // get the event object; if (e. srcElement) {// if srcElement is supported, it indicates IE; if (e. type = 'mouseover') {// if it is an over event; return e. fromeElement; // use from;} else if (e. type = 'mouseout') {// if it is out; return e. toElement; // use to;} else if (e. relatedTarget) {// If relatedTarget is supported, it indicates W3C; return e. relatedTarget ;}}

2. prevent default events

// Click the default behavior of a hyperlink and jump to the specified page; // This action can be blocked to implement custom operations; // The default action of canceling an event is also nonstandard, that is, false is returned; link. onclick = function () {alert ('Lee '); return false; // if false is returned directly, no jump will be made;} // PS: Although return false; this function can be implemented, but there is a vulnerability; // first, the Code must be written to the end, so that after the intermediate code is executed, the return false may not be executed; // second: return false write to the beginning, then the subsequent custom operation will fail; // solution: Stop the default action at the beginning, and the code can be executed later; function preDef (evt) {// cross-browser compatibility prevents default behavior; var e = evt | window. event; if (e. preventDefault) {e. preventDefault (); // W3C, blocking default behavior;} else {e. returnValue = false; // IE, blocking default behavior ;}}

3. context Menu event contextmenu // when we right-click the webpage, the windows built-in menu will automatically appear; // we can use the contextmenu event to modify the menu we specified; however, the premise is to cancel the default right-click action. addEvent (window, 'load', function () {var text = docuemnt. getElementById ('text'); addEvent (text, 'textmenu ', function (evt) {// Add a context menu event handler; var e = evt | window. event; preDef (e); // block the default behavior function; var menu = document. getElementById ('menu '); // find the custom menu object; menu. style. left = e. clientX + 'px '; // determines the position of the custom menu on the screen; menu. style. top = e. clientX + 'px '; menu. style. visibility = 'visable'; // set the properties of the custom menu to visible; addEvent (document, 'click', function () {// Add a click event handler to the document; docuemnt. getElementById ('mymenu '). style. visibility = 'den den '; // hide the custom menu ;});});});

4. beforeunload

// This event can help you give a corresponding prompt when you leave this page; "exit" or "return" operation; addEvent (window. 'beforeunload', function (evt) {var evt = event | window. event; var message = 'do you want to leave this page? '; Evt. returnValue = message; return message ;});

5. mousewheel and DOMMouseScroll

// Obtain the distance between the scroll wheel and the mouse. addEvent (docuemnt, 'mousewheel', function (evt) {// non-Firefox; alert (getWD (evt ));}); addEvent (docuemnt, 'dommousescroll ', function (evt) {// Firefox; alert (getWD (evt) ;}); function getWD (evt) {var e = evt | window. event; if (e. wheelDelta) {// The scroll value of the mousewheel event is saved in the wheelDelta; return e. wheelDelta;} else if (e. detail) {// The scroll value of the DOMMouseScroll event is saved in detail; return-evt. detail * 30; // maintain unified computing ;}}

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.