Deep understanding of JavaScript series (24): JavaScript and DOM (lower), javascriptdom

Source: Internet
Author: User

Deep understanding of JavaScript series (24): JavaScript and DOM (lower), javascriptdom
Introduction

In the previous chapter, we introduced the basic content of JavaScript and various aspects of DOM objects, including how to access node nodes. This chapter describes how to use DOM to operate elements and discuss browser event models.

Operation Element

In the previous chapter, we mentioned the access steps for a DOM node set or a single node. Each DOM node includes an attribute set, and most of the attributes provide abstraction for the corresponding functions. For example, if there is a text element with the ID attribute intro, you can easily change the color of the element through the dom api:

document.getElementById('intro').style.color = '#FF0000';

To understand the functions of this API, it is easy to understand it step by step:

Var myDocument = document; var myIntro = myDocument. getElementById ('intro'); var myIntroStyles = myIntro. style; // now, we can set the color: myIntroStyles. color = '# FF0000 ';

Now we have referenced the style object of the text, so we can add other CSS styles:

myIntroStyles.padding = '2px 3px 0 3px';  myIntroStyles.backgroundColor = '#FFF';  myIntroStyles.marginTop = '20px'; 

Here, we only need the basic CSS attribute name. The only difference is that if the CSS attribute name contains-, we need to remove it. For example, we need to replace margin-top with marginTop. For example, the following code does not work and throws a syntax error:

MyIntroStyles. padding-top = '10em '; // syntax error: // line in JavaScript-subtraction operator // and no such attribute name

Attributes can be accessed like arrays, so we can use this knowledge to create a function to change the style of any given element:

Function changeStyle (elem, property, val) {elem. style [property] = val; // use [] to access the property} // use the above function: var myIntro = document. getElementById ('intro'); // obtain the intro Text object changeStyle (myIntro, 'color', 'red ');

This is just an example, so this function may be useless. In terms of syntax, it will be faster to use it directly, for example (elem. style. color = 'red '). In addition to the style attribute, a node (or element) also has many other attributes that can be operated. If you use Firebug, click the DOM tab to view all attributes of the node (or element:

All attributes can be accessed through the dot mark (for example, Element. tabIndex ). Not all attributes are of the original data type (strings, numbers, Booleans, and so on). The sytle attribute is also an object containing its own attributes, and many element attributes are read-only, that is to say, they cannot be modified. For example, you cannot directly modify the parentNode attribute of a node. If you modify the read-only attribute, the browser throws an error: for example, the "setting a property that has only a getter" error is thrown ", but we need to pay attention to it.

Generally, DOM operations change the original content. There are several ways to implement this. The simplest thing is to use the innerHTML attribute, for example:

Var myIntro = document. getElementById ('intro'); // Replace the current content myIntro. innerHTML = 'new content for the <strong> amazing </strong> paragraph! '; // Add the content to the current content. myIntro. innerHTML + ='... some more content ...';

The only problem is that this method is not defined in the specification, and it is not defined in the DOM specification. If you are not disgusted, continue to use it, because it is much faster than other methods we will discuss below.

Node

When using DOM APIs to create content, pay attention to the two types of node nodes: Element nodes and text nodes. All node types are listed in the previous section, we need to pay special attention to these two types. You can use the createElement method to create an element, while createTextNode can be used to create a text node. The Code is as follows:

Var myIntro = document. getElementById ('intro'); // add content var someText = 'this is the text I want to add'; var textNode = document. createTextNode (someText); myIntro. appendChild (textNode );

Here we use the appendChild method to attach a new text node to a text field. This method is a little longer than the non-standard innerHTML method, but understanding these principles is still very important, here is a more detailed example of using the DOM method:

Var myIntro = document. getElementById ('intro'); // Add a new connection to a text node // first, create a new connection element var myNewLink = 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> // attachments content to the text node myIntro. appendChild (myNewLink );

In addition, there is an insertBefore method in the DOM for the content of the attachment before the node. Through insertBefore and appendChild, we can implement our own insertAfter function:

// 'Target' is an existing element in the DOM // 'bullet' is the new element to be inserted. function insertAfter (Target, Bullet) {target. nextSibling? Target. parentNode. insertBefore (bullet, target. nextSibling): target. parentNode. appendChild (bullet);} // 3 object expression used: // format: condition? Expression when the condition is true: expression when the condition is false

The above function first checks whether the next node at the same level of the target element exists. If yes, add a bullet node before the node. If no, the target is the last node, append the new node directly. Dom api does not provide insertAfter because it is really unnecessary-we can create it ourselves.

DOM operations have a lot of content. What you see above is only part of it.

Event

Browser events are the core of all web programs. With these events, we define the actions to take. If there is a button in the page, you need to verify that the form is valid before clicking this button, in this case, you can use the click event. The following lists the most standard event lists:

Note: As we mentioned in the previous chapter, DOM and JavaScript are two separate things. browser events are part of DOM APIs, not JavaScript.

Mouse events
  1. 'Mousedown'-When the mouse device presses the next element, the mousedown event is triggered.
  2. 'Mouseup'-The mouseup event is triggered when the mouse device pops up from the pressed element.
  3. 'Click'-The click event is triggered when the mouse clicks an element.
  4. 'Dblclick'-Double-click the element to trigger the dblclick event.
  5. 'Mouseover'-The mouseover event is triggered when you move the cursor over an element.
  6. 'Mouseout'-When the mouse leaves an element, the mouseout event is triggered.
  7. 'Mousemove'-The mousemove event is triggered when the mouse moves over an element but does not exit.
Keyboard Events
  1. 'Keypress'-This event is triggered when the key is pressed.
  2. 'Keydown'-This event is triggered when the key is pressed and before the keypress event.
  3. 'Keyup'-This event is triggered when the key is released after the keydown and keypress events.
Form Events
  1. 'Select'-This event is triggered when the text of the text field (input, textarea, etc.) is selected.
  2. 'Change'-This event is triggered when the control loses the input focus (or when the value is changed ).
  3. 'Submit'-This event is triggered when the form is submitted.
  4. 'Reset'-This event is triggered when the form is reset.
  5. 'Focus'-This event is triggered when the element gets the focus, usually from the mouse device or Tab navigation.
  6. 'Blur'-This event is triggered when the element loses focus, usually from the mouse device or Tab navigation.
Other events
  1. 'Load'-This event is triggered when the page is loaded (including content, images, frames, and objects.
  2. 'Resize'-This event is triggered when the page size changes (such as browser scaling ).
  3. 'Scroll'-This event is triggered when the page is rolled.
  4. 'Unload'-This event is triggered when all content is deleted from a page or frame (such as leaving a page ).

There are also a variety of events. The events shown above are the most commonly used events in JavaScript, and some events may be different across browsers. There are also some attribute events implemented by other browsers, such as DOMContentLoaded or DOMMouseScroll implemented by Gecko. For details about Gecko, see here.

Event Processing

Before using these events, you must register these event handles, the following example describes how to handle an event. The following example shows a basic event registration model:

Basic event registration:

<!-- HTML -->  <button id="my-button">Click me!</button>  
// JavaScript: var myElement = document. getElementById ('My-click'); // event processing handle: function buttonClick () {alert ('you just clicked the button! ');} // Register the event myElement. onclick = buttonClick;

Use the document. getElementById command to obtain the button object through ID = my-button, create a processing function, and assign the function to the onclick attribute of the DOM. That's easy!

Basic event registration is very simple. You can use the on prefix before the event name as the DOM attribute. This is the basic core of event processing, but the following code is not recommended:

<button onclick="return buttonClick()">Click me!</button>

The preceding Inline event processing method does not use page maintenance. We recommend that You encapsulate these processing functions in a separate js file for the same reason as the CSS style.

Advanced event registration:

Don't be confused by the title. "advanced" doesn't mean it is easy to use. In fact, the basic event registration discussed above is the method we use most of the time, but there is a limit: you cannot bind multiple processing functions to an event. This is why we want to explain this section:

When running this model, you bind multiple processing handles to an event. That is to say, when an event is triggered, multiple functions can be executed. In addition, this model also allows you to easily delete a bound handle.

Strictly speaking, there are two different models: W3C model and Microsoft model. W3C model except IE supports all modern browsers, while Microsoft model only supports IE, the code for using the W3C model is as follows:

// Format: target. addEventListener (type, function, useCapture); // example: var myIntro = 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: var myIntro = document. getElementById ('intro'); myIntro. attachEvent ('onclick', introClick );

The introClick code is as follows:

function introClick() {      alert('You clicked the paragraph!');  }

In fact, to make a general function, we can customize a function to support cross-browser:

function addEvent(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 attributes of attachEvent and addEventListener, who can use them. Both models support the delete handle function. See the removeEvent function below.

function removeEvent(elem, type, fn) {    if (elem.detachEvent) {        elem.detachEvent('on' + type, fn);        return;    }    if (elem.removeEventListener) {        elem.removeEventListener(type, fn, false);    }}

You can use:

var myIntro = document.getElementById('intro');addEvent(myIntro, 'click', function () {    alert('YOU CLICKED ME!!!');});

Note that we have passed in an anonymous function as the third parameter, and JavaScript runs our definition and executes anonymous functions. This anonymous function is especially suitable for passing parameters, in fact, we can also pass a famous function (the Code is as follows), but your function is easier to do.

If you only want to trigger a function during the first click, you can do this:

// Note: the premise is that we have set the addEvent/removeEvent function // (defined before use) var myIntro = document. getElementById ('intro'); addEvent (myIntro, 'click', oneClickOnly); function oneClickOnly () {alert ('Wow! '); RemoveEvent (myIntro, 'click', oneClickOnly );}

After the first trigger, we immediately delete the handle, but it is difficult to delete its own reference if there is an anonymous function, but it can actually be done in the following form (just a little troublesome ):

addEvent(myIntro, 'click', function () {    alert('WOW!');    removeEvent(myIntro, 'click', arguments.callee);}); 

Here we have the callee attribute of the arguments object. The arguments object contains all the passed parameters and the function itself (callee), so that we can safely delete our reference.
There are a few other differences between W3C and Microsoft models. For example, this is generally the context of the element in the function when an event is triggered, that is, this references the element itself, there is no problem in the basic event registration and W3C model, but an error may occur in the implementation of the Microsoft model. Please refer to the following code:

Function myEventHandler () {this. style. display = 'none';} // normal operation. this indicates the element myIntro. onclick = myEventHandler; // normal operation. this indicates the element myIntro. addEventListener ('click', myEventHandler, false); // this indicates that the Window object myIntro. attachEvent ('onclick', myEventHandler );

There are some ways to avoid this problem. The simplest way is to use the previous basic event registration method, or to make a general addEvent, for general code, see John Resig or Dean Edward's article.

Event object

Another important thing is the Event object. when an Event occurs, the Event object is automatically available in the function when a function is started. This object contains a lot of information about Event triggering, however, IE is not implemented in this way, but it is implemented by itself. IE uses the event attribute in the Global Object window to include this information. Although this is not a big problem, we also need to pay attention to it, the following code is compatible:

Function myEventHandler (e) {// note parameter e // when this function is called, e is the event object (W3C implementation) // code compatible with IE e = e | window. event; // now e can be compatible with various browsers} // You can freely bind events here

Here, we use the OR operator to determine whether the e object (Event object) exists. If e does not exist (null, undefined, 0, etc. event is assigned to e. Otherwise, e is used. Using this method, you can quickly get the real Event object in multiple browsers. if you do not like this method, you can use the if statement to process it:

If (! E) {e = window. event;} // no else statement, because e has been defined in other browsers.

In addition, the commands and attributes of the Event object are very useful. Unfortunately, they are not fully compatible with browsers, for example, if you want to cancel the default behavior, you can use the preventDefault () method in the Event object, but IE has to use the returnValue attribute value of the object for control. The compatible code is as follows:

Function myEventHandler (e) {e = e | window. event; // prevents default behavior if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false ;}}

For example, when you click a connection, the default behavior is to navigate to the address defined in href, but sometimes you want to disable this default behavior through returnValue and preventDefault, many properties in the Event object are incompatible in the browser, so these compatibility codes need to be processed in many cases.

Note: at present, many JS class libraries have encapsulated e. preventDefault code, that is, the Code is available in IE, but it is still implemented using returnValue in principle.

Event bubbling

Event bubbling means that the event is triggered by the DOM to bubble up. First, you must know that not all events have bubbles. When an event is triggered on a target element, the event triggers the ancestor node elements one by one until the top element:

If a connection is clicked, the click event that triggers the connection is triggered, and then the click event of p is triggered to trigger the click Event of the div and body. The sequence remains unchanged and is not necessarily triggered at the same time.
In this way, you can use this feature to process your own logic and stop bubbling at any time. For example, if you only want to bubble to a text node, instead of further bubbling, you can stop the bubble in the click event handler function of p:

Function myParagraphEventHandler (e) {e = e | window. event; // stop bubbling up if (e. stopPropagation) {// W3C implementation e. stopPropagation ();} else {// IE implementation e. cancelBubble = true ;}}// use our custom addEvent function to bind myParagraphEventHandler to the click Event: addEvent (document. getElementsByTagName ('P') [0], 'click', myParagraphEventHandler );

Event Delegate

For example, if you have a large table with many rows, binding click events on each <tr> is a very dangerous idea, because performance is a big problem. The popular practice is to use event delegation. The event Delegate describes how to bind an event to a container element, and then trigger an event by judging the type of the target sub-element to be clicked.

Var myTable = document. getElementById ('My-table'); myTable. onclick = function () {// processing browser compatibility e = e | window. event; var targetNode = e.tar get | e. srcElement; // test if TR is clicked, if (targetNode. nodeName. toLowerCase () = 'tr') {alert ('You clicked a table row! ');}}

Event delegation depends on Event bubbling. If the event is disabled before it is bubbling to the table, the above Code will not work.

Summary

In this chapter, we cover DOM element operations and related browser event models. I hope you can have a better understanding of DOM. If you have any questions, please leave a message for discussion.

Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.

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.