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.
Reference: http://net.tutsplus.com/tutorials/javascript-ajax/javascript-and-the-dom-lesson-2/
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:
VaRMydocument = document;
VaRMyintro = mydocument. getelementbyid ('intro ');
VaRMyintrostyles = 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 exampleCodeIt does not work and will throw a syntax error:
Myintrostyles. Padding-Top = '10em ';
//Syntax error:
//Horizontal line in Javascript-subtraction Operator
//And there is 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:
FunctionChangestyle (ELEM, property, Val ){
ELEM. Style [property] = val;//Use [] to access attributes
}
//Use the above functions:
VaRMyintro = Document. getelementbyid ('intro ');//Get 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 will throw 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:
VaRMyintro = Document. getelementbyid ('intro ');
//Replace the current content
Myintro. innerhtml = 'new content for the <strong> amazing </strong> paragraph! ';
//Add 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:
VaRMyintro = Document. getelementbyid ('intro ');
//Add content
VaRSometext = 'this is 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 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 new connection to 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 to text nodes
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.
FunctionInsertafter (target, bullet ){
Target. nextsibling?
Target. parentnode. insertbefore (bullet, target. nextsibling)
: Target. parentnode. appendchild (bullet );
}
//3 object expressions are 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 event
Browser events are all webProgramCore, through these events we define the behavior to happen, if there is a button in the page, you need to verify whether the form is valid before clicking this button, then you can use the click event, the most standard event list listed below:
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
- 'Mousedown'-When the mouse device presses the next element, the mousedown event is triggered.
- 'Mouseup'-The mouseup event is triggered when the mouse device pops up from the pressed element.
- 'Click'-The click event is triggered when the mouse clicks an element.
- 'Dblclick'-Double-click the element to trigger the dblclick event.
- 'Mouseover'-The Mouseover event is triggered when you move the cursor over an element.
- 'Mouseout'-When the mouse leaves an element, the mouseout event is triggered.
- 'Mousemove'-The mousemove event is triggered when the mouse moves over an element but does not exit.
Keyboard Events
- 'Keypress'-This event is triggered when the key is pressed.
- 'Keydown'-This event is triggered when the key is pressed and before the keypress event.
- 'Keyup'-This event is triggered when the key is released after the keydown and keypress events.
Form Events
- 'Select'-This event is triggered when the text of the text field (input, textarea, etc.) is selected.
- 'Change'-This event is triggered when the control loses the input focus (or when the value is changed ).
- 'Submit'-This event is triggered when the form is submitted.
- 'Reset'-This event is triggered when the form is reset.
- 'Focus'-This event is triggered when the element gets the focus, usually from the mouse device or tab navigation.
- 'Blur'-This event is triggered when the element loses focus, usually from the mouse device or tab navigation.
Other events
- 'Load'-This event is triggered when the page is loaded (including content, images, frames, and objects.
- 'Resize'-This event is triggered when the page size changes (such as browser scaling ).
- 'Scroll'-This event is triggered when the page is rolled.
- '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-->
<ButtonID= "My-button">Click me!</Button>
//Javascript:
VaRMyelement = Document. getelementbyid ('My-click ');
//Event handling handle:
FunctionButtonclick (){
Alert ('you just clicked the button! ');
}
//Register an 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:
<ButtonOnclick= "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:
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 );
The introclick code is as follows:
FunctionIntroclick (){
Alert (you clicked the paragraph! ');
}
In fact, to make a general function, 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 attributes of attachevent and addeventlistener, who can use them. Both models support the delete handle function. See the removeevent function below.
FunctionRemoveevent (ELEM, type, FN ){
If(ELEM. detachevent ){
ELEM. detachevent ('on' + type, FN );
Return;
}
If(ELEM. removeeventlistener ){
ELEM. removeeventlistener (type, FN,False);
}
}
You can use:
VaRMyintro = 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.
//(It can be used only after it is defined)
VaRMyintro = Document. getelementbyid ('intro ');
Addevent (myintro, 'click', oneclickonly );
FunctionOneclickonly (){
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:
FunctionMyeventhandler (){
This. Style. Display = 'none ';
}
//It works normally. This indicates this element.
Myintro. onclick = myeventhandler;
//It works normally. This indicates this element.
Myintro. addeventlistener ('click', myeventhandler,False);
//Abnormal. At this time, this indicates 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 make another general addevent. For general code, see John resig or Dean Edward'sArticle.
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 when an event is triggered, but IE does not implement this, but it is implemented by itself. IE browser uses the event attribute under the Global Object window to contain this information, although it is not a big problem, we also need to note that the following code is compatible:
FunctionMyeventhandler (e ){
//Note that 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 obtain 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:
FunctionMyeventhandler (e ){
E = E | window. event;
//Prevent 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.
VaRMytable = Document. getelementbyid ('My-table ');
Mytable. onclick =Function(){
//Browser compatibility
E = E | window. event;
VaRTargetnode = e.tar GET | E. srcelement;
//Test. If you click TR, It is triggered.
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.
Transferred from: Uncle Tom