In-depth understanding of the JavaScript series: JavaScript and Dom (bottom)

Source: Internet
Author: User
Tags access properties

in the previous chapter, we introduced the basic content of JavaScript and the various aspects of DOM objects, including how to access node nodes. In this chapter we will explain how to manipulate elements through the DOM and discuss the browser event model. This article references: http://net.tutsplus.com/tutorials/javascript-ajax/javascript-and-the-dom-lesson-2/The previous section of the action element we refer to the DOM node collection or the access steps of a single node, each DOM node includes a collection of attributes, and most of the properties provide an abstraction for the appropriate functionality. For example, if you have a text element with an id attribute intro, you can easily change the color of the element through the DOM API: document.getElementById (' intro '). Style.color = ' #FF0000 'in order to understand the functionality of this API, it is very easy to understand how to do this in a separate step-by-step perspective:varMyDocument =document; varMyintro = Mydocument.getelementbyid (' intro ')); varMyintrostyles =Myintro.style; //now, we can set the color:Myintrostyles.color = ' #FF0000 'now, we have a reference to the text's style object, so we can add another CSS style: myintrostyles.padding= ' 2px 3px 0 3px '; Myintrostyles.backgroundcolor= ' #FFF '; Myintrostyles.margintop= ' 20px 'Here we just want the basic CSS property name, the only difference is that the name of the CSS property-If so, you need to remove it, such as replacing margin-with MarginTop.top. For example, the following code is not working and throws a syntax error: myintrostyles.padding-top = ' 10em '; //A syntax error has occurred://in JavaScript, horizontal-is the subtraction operator.//and there's no such attribute nameproperties can be accessed like arrays, so using this knowledge we can create a function to change the style of any given element:functionChangestyle (Elem, property, Val) {Elem.style[property]= Val;//use [] to access properties}//Use the above functions:varMyintro = document.getElementById (' intro ');//Get Intro Text ObjectChangestyle (Myintro, ' Color ', ' red '); This is just an example, so the function may be useless, syntactically speaking, directly or quickly, for example (Elem.style.color=' Red '). In addition to the style property, a node (or element) has many other properties to manipulate, and if you use Firebug, Click on the Dom tab to see all of the properties of that node (or element): All properties can be accessed using the dot identifier (for example: Element.tabindex). Not all properties are raw data types (strings, numbers, booleans, and so on), the Sytle property is also an object that contains its own properties, and many of its properties are read-only, which means that their values cannot be modified. For example, you cannot directly modify the ParentNode property of a node, and if you modify the read-only attribute, the browser throws an error: for example, throw the error "setting a property that has only a getter", just what we need to be aware of. Usually DOM operations change the original content, there are several ways to implement this, the simplest is to use the innerHTML property, for example:varMyintro = document.getElementById (' intro ')); //Replace the current contentmyintro.innerhtml = ' New content for the <strong>amazing</strong> paragraph! '; //add content to current contentmyintro.innerhtml + = ' ... some more content ... 'The only problem is that the method is not defined in the specification and is not defined in the DOM specification, and if you don't resent it, keep using it, because it's much faster than what we're going to talk about in other ways. When node nodes create content through the DOM API, there are 2 types of node nodes, one is the element node, the other is the text node, and the previous section already lists all the node types, both of which require our special attention now. Creating elements can be done through the createelement method, while creating a text node can use createTextNode, the corresponding code is as follows:varMyintro = document.getElementById (' intro ')); //Add ContentvarSometext = ' The text I want to add '; varTextnode =document.createTextNode (Sometext); Myintro.appendchild (Textnode); Here we use the AppendChild method to attach a new text node attachment to a text field, which is a bit longer than a nonstandard innerHTML method, but it's still important to understand these principles, Here's a more detailed example of using DOM methods:varMyintro = document.getElementById (' intro ')); //add a new connection to a text node//First, create a new connection elementvarMynewlink = document.createelement (' a ');//<a/>Mynewlink.href = ' http://google.com ';//<a href= "http://google.com"/>Mynewlink.appendchild (document.createTextNode (' Visit Google '))); //<a href= "http://google.com" >visit google</a>  //to attach a content attachment to a text nodeMyintro.appendchild (Mynewlink); there is also a InsertBefore method in the DOM to re-node the contents of the previous attachment, With InsertBefore and appendchild we can implement our own InsertAfter function://' Target ' is an existing element in the DOM .//' Bullet ' is the new element to insert  functionInsertAfter (target, bullet) {target.nextsibling?Target.parentNode.insertBefore (Bullet, target.nextsibling): Target.parentNode.appendChild (bullet); }    //3-Mesh expressions are used://format: Condition? expression when the condition is true: expression when the condition is falseThe above function first checks to see if the target element's sibling next node exists, if there is a bullet node in front of the node, if it does not exist, it means that the target is the last node, directly behind the append new node. The DOM API doesn't provide InsertAfter because it's really unnecessary-we can create it ourselves. Dom operations have a lot of content, and what you see above is just part of it. Event event Browser events are at the heart of all Web programs, and through these events we define what is going to happen, and if there is a button on the page, you need to verify that the form is legitimate before clicking on the button, then you can use the Click event. The most standard list of events listed below: Note: As we said in the previous chapter, the DOM and JavaScript languages are 2 separate things, and browser events are part of the DOM API, not part of JavaScript. Mouse event ' MouseDown ' – the mouse device triggers the MouseDown event when an element is pressed. ' MouseUp ' – triggers the MouseUp event when the mouse device bounces from the pressed element. ' Click ' – the Click event is triggered when the mouse clicks on an element. ' DblClick ' – The DblClick event is triggered when the mouse double-clicks the element. ' MouseOver ' – triggers the MouseOver event when the mouse moves over an element. ' Mouseout ' – triggers the Mouseout event when the mouse leaves from an element. ' MouseMove ' – triggers the MouseMove event when the mouse moves on an element but does not leave. Keyboard event ' KeyPress ' – The event is triggered when the button is pressed. ' KeyDown ' – The event is triggered when the key is pressed and before the KeyPress event. ' KeyUp ' – triggers the event when the key is released, after the KeyDown and KeyPress events. Form event ' SELECT ' – The Text field (input, textarea, etc.) is selected to trigger the event. ' Change ' – triggers the event when the control loses input focus (or when the value is changed). ' Submit ' – The event is triggered when the form is submitted. ' Reset ' – This event is triggered when the form is reset. ' Focus ' – triggers the event when the element receives focus, usually from a mouse device or tab navigation. ' Blur ' – triggers the event when the element loses focus, usually from a mouse device or tab navigation. Other event ' Load ' – This event is triggered when the page has finished loading (including content, picture, frame, object)。 ' Resize ' – this event is triggered when the page size changes (such as browser scaling). ' Scroll ' – This event is triggered when the page scrolls. ' Unload ' – triggers the event when all content is deleted from the page or frame (for example, leaving a page). There are many different kinds of events, the events shown above are the ones we use most frequently in JavaScript, and some events may be different across browsers. There are also some property events implemented by other browsers, such as domcontentloaded or Dommousescroll implemented by Gecko, and a detailed list of events for Gecko, see here. Event handling we have the event, but not yet how to manage the handling functions and events, before you use these events, you first register these event handles, then describe what to do when the event occurs, and the following example shows a basic event Registration model: Basic Event Registration:<!--HTML--<button id= "My-button" >click me!</button>//JavaScript:varMyElement = document.getElementById (' My-button '));//Event handling handle:functionButtonClick () {alert (' You just clicked the button! ');}//Registering EventsMyelement.onclick =ButtonClick; Use the document.getElementById command, through the ID=my-The button Gets the button object, and then creates a handler function that then assigns the function to the OnClick property of the DOM. It's so easy! Basic event Registration is very simple, adding a prefix to the event name is used as a DOM attribute, which is the basic core of event handling, but the following code I do not recommend using:<button onclick= "return ButtonClick ()" >click me!</button>The above inline event handling method does not take advantage of page maintenance, it is recommended that these processing functions are encapsulated in a separate JS file for the same reason as the CSS style. Advanced Event Registration: Do not be confused by the title, "Advanced" does not mean to use, in fact, the basic event registration discussed above is the way we used most of the time, but there is a limitation: can not bind more than one processing function to an event. That's why we're going to explain this section: the model runs you to bind multiple handles to an event, which means that multiple functions can be executed when an event is triggered, and that the model also allows you to easily delete an already bound handle. Strictly speaking, there are 2 different models: the Web model and Microsoft model, in addition to IE, the model is supported by all modern browsers, and Microsoft model only supports IE, the use of the model Code is as follows://format: Target.addeventlistener (type, function, usecapture); //Example:varMyintro = document.getElementById (' intro ')); Myintro.addeventlistener (' Click ', Introclick,false); The code for using the IE model is as follows://format: target.attachevent (' on ' + type, function); //Example:varMyintro = document.getElementById (' intro ')); Myintro.attachevent (' OnClick ', Introclick); Introclick's code is as follows:functionIntroclick () {alert (' You clicked the paragraph! '); In fact, to make a generic statement, we can customize a function to support cross-browser:functionaddevent (elem, type, fn) {if(elem.attachevent) {elem.attachevent (' On ' +type, fn); return; }    if(Elem.addeventlistener) {Elem.addeventlistener (type, FN,false); }} This function first checks the attachevent and AddEventListener properties and who can use them, both types of models support the removal of the handle function, referring to the following removeevent function. functionremoveevent (elem, type, fn) {if(elem.detachevent) {elem.detachevent (' On ' +type, fn); return; }    if(Elem.removeeventlistener) {Elem.removeeventlistener (type, FN,false); }} You can use this:varMyintro = document.getElementById (' intro ')); Addevent (Myintro,' Click ',function() {alert (' You CLICKED ME!!! ');}); Notice that we passed in an anonymous function as the third parameter, and JavaScript runs our definition and execution of anonymous functions, which are particularly well-suited as arguments, and we can actually pass the known functions (code below), but your functions are easier to do. If you just want to trigger a function at the first click, you can do this://Note: The premise is that we're set on the Addevent/removeevent function//(defined to use OH)varMyintro = document.getElementById (' intro ')); Addevent (Myintro,' Click ', oneclickonly);functiononeclickonly () {alert (' Wow! '); Removeevent (Myintro,' Click ', oneclickonly);} After the first trigger, we delete the handle immediately, but with an anonymous function it is difficult to delete the reference itself, but it can actually be done in the following form (just a bit of a hassle): Addevent (Myintro,' Click ',function() {alert (' Wow! '); Removeevent (Myintro,' Click ', Arguments.callee);}); Here we have the callee property of the arguments object, and the arguments object contains all the arguments passed in and the function itself (callee) so that we can safely delete our references. There are a few other differences about the company and Microsoft model, such as this, in the event of triggering events in the function of this is generally the context of the element, it is said that this refers to the element itself, in the basic event registration and the model is not a problem, but in the implementation of the Microsoft model can be error, Please refer to the following code:functionMyEventHandler () { This. style.display = ' None ';}//normal work, this is the element that represents theMyintro.onclick =MyEventHandler;//normal work, this is the element that represents theMyintro.addeventlistener (' Click ', MyEventHandler,false);//not normal, this time the this is represented by the Window objectMyintro.attachevent (' onclick '), MyEventHandler); Here are some ways to avoid this problem, the simplest way is to use the previous basic event registration method, or to do a general addevent, general code please refer to John Resig or Dean Edward's article. Another very important element of the event object is the event object, which, when the event occurs, starts a function that is automatically available within the function, which contains a lot of information when the event is triggered, but IE is not so implemented, but it is implemented by itself, IE is included with the event property under the Global Object window, although not a big problem, but we also need to note that the following code is compatible:functionMyEventHandler (e) {//Note the parameter e    //when the function is called, E is the event object (the implementation of the    //code compatible with IEE = e | |window.event; //now E can be compatible with a variety of browsers}//We're free to bind events here.This determines whether the E object (the event object) exists and we use the OR operator: If E does not exist (NULL, undefined,0, etc.), the window.event is assigned to E, otherwise it continues with E. This way you can quickly get real event objects in multiple browsers, and if you don't like this way, you could use the IF statement to handle:if(!e) {e=window.event;} //there is no else statement because E is already defined in other browsersIn addition, the command and properties under the event object are useful, unfortunately not all compatible browsers, such as when you want to cancel the default behavior when you can use the Preventdefault () method in the Event object, But IE has to use the object's ReturnValue attribute value to control, the compatible code is as follows:functionMyEventHandler (e) {e= e | |window.event; //Prevent default behavior    if(E.preventdefault) {e.preventdefault (); } Else{E.returnvalue=false; For example, when you click on a connection, the default behavior is to navigate to the address defined in the href, but sometimes you want to disable this default behavior, through ReturnValue and Preventdefault can be implemented, the event object many properties in the browser is incompatible, So many times you need to deal with these compatibility codes. Note: Many JS libraries are now packaged with the E.preventdefault code, which means it is available in IE, but the principle is still used returnvalue to achieve. The event bubbling event bubbles up when the event is triggered by bubbling up through the DOM, first knowing that not all events are bubbling. When an event is triggered on a target element, the event triggers a one by one triggering of the ancestor node element until the topmost element: If a connection is clicked, triggers the Click event that triggers the connection, and then triggers the Click event of P, which then triggers the click event of the div and body. The order is constant, and it is not necessarily triggered at the same time. This way you can use this feature to handle your own logic, and you can stop bubbling at any time, for example, if you just want to bubble up to a text node and no longer bubble further, you can stop bubbling in the P's Click event handler:functionMyparagrapheventhandler (e) {e= e | |window.event; //Stop bubbling Up    if(e.stoppropagation) {//The realization of thee.stoppropagation (); } Else {        //IE ImplementationE.cancelbubble =true; }}//bind the Myparagrapheventhandler to the click event using our custom addevent function:Addevent (document.getElementsByTagName (' P ') [0], ' click ', Myparagrapheventhandler); event delegate For example, if you have a large table with a lot of rows, in each<tr>Binding a point-and-click event is a very dangerous idea because performance is a big problem. The popular practice is to use event delegates. An event delegate describes an event that is bound to a container element and then triggered by judging the type of the target child element that is clicked. varmyTable = document.getElementById (' my-table ')); Mytable.onclick=function () {    //Handling Browser CompatibilityE = e | |window.event; varTargetNode = E.target | |e.srcelement; //Test if you click on TR to trigger    if(targetNode.nodeName.toLowerCase () = = = ' TR ') {alert (' You clicked a table row! '); }} The event delegate relies on event bubbling, and if the event bubbles before the table is disabled, the code above will not work. In this chapter we cover the operation of DOM elements and the related browser event model, and we hope that we can have a better understanding of DOM. Have any questions, please leave a message to discuss. Synchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of the JavaScript series: JavaScript and Dom (bottom)

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.