JavaScript (Core, BOM, DOM)

Source: Internet
Author: User
Tags array length script tag tag name hosting

http://www.flyne.org/article/407

JavaScript (Core, BOM, DOM)

JavaScript is an object- and event-driven , client-side scripting language. Has the following characteristics:

      • Interactivity
      • Security (no direct access to local hard disk)
      • Cross-platform (as long as the browser can parse JS can be executed, and platform-independent)

1, JavaScript and Java are different! ① belongs to: Netscape and Sun② Object-based and object-oriented ③js can directly parse execution, Java needs to be compiled before running ④JavaScript is a weakly typed language, Java is a strongly typed language.

2, the implementation of JavaScript includes the following 3 parts:

1) Core (ECMAScript): Describes the syntax and basic object of JS.

2) Document Object Model ☆ (DOM): Methods and interfaces for handling Web page content

3) Browser object Model (BOM): Methods and interfaces for interacting with the browser

ECMAScript Extended Knowledge:

①ecmascript is a standard, JS is just one of its implementations, other implementations include ActionScript.

② "ECMAScript can provide core scripting capabilities for different kinds of hosting environments ...", that is, ECMAScript is not tied to a specific hosting environment, such as JS's hosting environment is a browser, as the host environment is flash.

③ecmascript describes the following: syntax, type, statement, keyword, reserved word, operator, object.

3. Using JavaScript in HTML

1) write the JS code directly inside the <script></script> tag

2) Direct introduction of external JS files via the src attribute of the script tag

Note: If both methods are present, the JS code defined inside the tag will not be executed.

JS Core

4. JS data type (☆)

Using the VAR keyword to declare a variable in JS, the type of the variable is determined by its assigned value . The data type in JS is divided into the original data type (5 kinds) and the reference data type (object type).

1) 5 Raw data types: Undefined, Null, Boolean, number, and string. It is important to note that the string in JS belongs to the original data type.

2) typeof operator: View variable type, call the typeof operator on a variable or value returns one of the following values:

      • undefined– If the variable is of type undefined

      • boolean– If the variable is of type Boolean

      • number– If the variable is of type number

      • string– If the variable is of type String

      • object– If the variable is a reference type or a Null type

3) solve the problem of reference type judging by instanceof operator

4) The definition of a type in JS: A set of values. There are two values for the Boolean type: True, False. Both the undefined and the null types have only one value, undefined and null, respectively.

5)Null is considered a placeholder for the object , and the TypeOf operator returns "Object" for a null value.

6) The original data type and the reference data type variables are stored in memory as follows:

5. Local variables and global variables

A variable declared in a function can only be used in a function, and when you exit a function, the variable is released, which is called a local variable . Because each local variable is only valid in its own function, you can use a variable with the same name in a different function.

If you declare a variable outside of a function, all functions in the page can use it. After the global variables are declared, they begin to take effect. The variable will not be invalidated until the page is closed.

Note: In the JS language, the variables declared in the code block belong to the global variable.

6, Array (two ways to create)

1) var arr = [123, "ABC", True,null]

2) var arr = new Array (4); To create an array with an array length of 4

var arr = new Array (123, "abc", true,null);//equivalent to 1)

Attention:

In ①js, array element types can be inconsistent.

②js, the length of the array can be changed dynamically.

③ then the above code, typeof arr and arr instanceof Array output object and True respectively.

7. Functions

Features: keyword function; you do not need to specify a return value type; The parameter list declaration does not require the VAR keyword; there is no function overload; the arguments array (implicitly defined) can be called directly inside the function, which stores the list of arguments, and the function name represents a reference type. can be used (function name instanceof function) test; the print function reference outputs the entire definition.

8. Dynamic functions and anonymous functions

1) Dynamic functions are defined by JS's built-in object function . The form is: New Function (Arg1, arg2), which can be specified dynamically because arg1 and arg2 are variables. Such as:

var run = new Function ("X, Y", "return x+y;");

2) anonymous function: no function name, such as: var run = function (x, y) {return x+y;};

Note: Printing a reference to a dynamic function reveals that the dynamic function is also an anonymous function.

9, JS object (need new one object)

1) String objects , methods are divided into two categories: ① HTML-related ② are similar to strings in Java. Check the documentation specifically.

2) Array Object , some common methods:

      • Concat () The Concat () method of the same string.

      • Join () is the opposite of the split () method of String.

      • Pop (), push () in the same stack of the stack, press stack.

      • Sort () sorts the array elements.

3) Date Object

GetTime The (),date.parse(datestring) method returns the timestamp.

Watch Example: add onload= "startTime () to body;" You can dynamically display the current time in the #div_1 block

1

2

3

4

5

6

7

8

function   startTime () {

     var   Date =  new   date ();

     var   h = date.gethours ();

     var   m = Date.getminutes ();

     var   s = date.getseconds ();

     document.getElementById ( "div_1" ). innerhtml=h+ ":" +m+ ":" +s;

     setTimeout ( "StartTime ()" , +);

}

4) The Math object, mostly static methods, is commonly used with random (), ceil (x)/floor (x)/round (x) methods.

5) RegExp object: This object represents a regular expression for string matching

Two ways to create RegExp objects:

Mode one,new one RegExp object:var regExp = new RegExp ("[a-za-z0-9]{3,8}");

Mode two, by direct amount Assignment:var regExp =/^[a-za-z0-9]{3,8}$/;

The exact wording of the regular expression when using the query document.

Common method: Test (String), which returns TRUE or false.

10. Global functions

encodeURI / decodeURI: encoding and decoding URI

encodeURI can be used as a whole when making URL jumps

encodeuricomponent / decodeuricomponent: Encoding and decoding URI component

You need to use encodeURIComponent when passing parameters

Escape / unescape: Unicode Encoding of strings

IsNaN: Checks whether a value is Nan (not a number, non-numeric)

parseint,parsefloat: Resolving strings to integers and floating-point numbers

eval: Computes the JS string and executes it as script code.

BOM (Browser object model)

11. BOM (Browser object model)

1) Window object: windows open in Browser

① If the document contains a frame (frame or iframe label), the browser creates a Window object for the HTML document and creates an additional window object for each frame.

②window.frames returns all named frames in the window

③parent is the parent window (if the window is a top-level window, then Parent==self==top)

Top is the top-level parent window (some windows have several layers of frameset or IFRAME)

Self is the current window (equivalent Windows)

Opener is the window that opens the current window with the Open method

④ methods related to message boxes: Alert (String), confirm (String), Prompt (string)

Two types of timers :setTimeout(code,latency) and setinterval(code,period)

Note: settimeout executes code only once, and if multiple calls are made, you can let code itself call SetTimeout () again, and Setinteval () calls code until Clearinterval () is called.

2) Locationobject : Contains the current URL information. Focus on the href attribute of the Location object to set or return the full URL.

3) HistoryObject : Mainly back ()/forward () and Go () method, almost not used.

2nd page (total 2 pages) DOM (Document Object model)

The DOM is a set of standards used by the organization to access and manipulate XML and HTML documents . The wide-range DOM is divided into 3 different parts/levels (Parts/levels):

      • Core DOM: A standard model for any structured document (no research)

      • XML DOM: FOR XML ...

      • HTML DOM: for HTML ...

12. XML Dom and HTML DOM

HTML and XML:
HTML: Hypertext Markup Language, tags are limited, each tag has its own fixed meaning, mainly for the display of information.
XML: Extensible Markup Language, customizable markup, strong extensibility, primarily for information storage and delivery

1) The XML DOM and HTML DOM define standard methods (interfaces) for accessing and manipulating XML and HTML documents, respectively.

2) HTML documents conform to the XML syntax standard, so you can use the XML DOM API to parse the HTML (which is cumbersome), and the following examples are parsed using the HTML DOM and the XML DOM, respectively.

3) If HTML is treated as XML, carriage returns, spaces, and tabs are not ignored.

13. DOM node tree model (take HTML DOM tree as an example)

1) The DOM model sees the entire document (XML document and HTML document) as a tree structure and represents it with a document object.

2) DOM specifies that each component in the document is a node:

Document node: represents the entire document

ELEMENT node: A tag in a document

Text node (text): a literal in markup

Attribute node (Attr): Represents an attribute, an element has an attribute

3) node is the parent interface for all nodes , which defines a common set of properties and methods, as follows:

14. DOM node three major attributes (XML DOM)

1) nodeName: element nodes, attribute nodes, text nodes return the name of the element, the name of the property, and the #text string, respectively.

2) NodeType: The nodeType values for element nodes, attribute nodes, and text nodes are 1, 2, 3, respectively.

3) NodeValue: The return values of element nodes, attribute nodes, and text nodes are null, property values, and text node contents, respectively.

15. Common Properties and methods of document objects

Property:

DocumentElement: Returns a reference to the document root element. Return

Method:

getElementById (): ☆ Get element based on ID

Getelementsbyname (): Gets the element according to the Name property, which is obtained by ID when there is no name.

getElementsByTagName (): Obtained by tag name

CreateElement (), createTextNode (): Creates an element node, a text node.

16. Practice

Eg1, get code

1

2

3

4

5

6

7

8

9

vareleNode = document.getElementById("test");

alert(eleNode.firstChild.nodeValue);

alert(eleNode.childNodes[0].nodeValue);

varh1Obj = document.getElementById("test");

alert(h1Obj.innerHTML);

alert(h1Obj.innerText);

EG2, print the contents of the text in

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

functionprintNode(node){

    if(node.nodeType == 3){

        alert(node.nodeValue.trim());

    }elseif(node.nodeType == 1){

        varnodes = node.childNodes;

        for(vari = 0;i <nodes.length;i ++){

            printText(nodes[i]);

        }

    }

}

varliNodes = document.getElementsByTagName("li");

for(vari = 0;i < liNodes.length;i ++){

    printNode(liNodes[i]);

}

17. Dom Common operations (XML DOM) ☆

1) Get node

① Gets the element node: obtained by three methods of the Document object

② Gets the attribute node: the attribute node is attached to the element node and can be obtained through the GetAttributeNode(attrname) method of the element node, or through getattribute(attrname ) to get the property value directly. (In contrast to the setattribute (Attrname, AttrValue) method of the element interface, if the attribute does not exist, it is added directly to the element node)

③ Gets the text node: The text node is a child of the element node, which can be obtained through the childnodes () [index] method provided by the element node (elements interface).

2) Change node

① changes the value of the attribute node: The property value can be modified directly through the nodevalue of the attribute node, or by the SetAttribute() method of the element node (17.1.2 section).

② changes the value of the text node: it is directly modified by the nodevalue of the text node.

3) Delete node

① Delete element node: To delete an element node A, you need to get the parent Node B of a, the parent node can be obtained through the method in 17.1.1, or it can be obtained directly through the ParentNode property of a (recommended). Call B's removechild(a) to delete the A node.

② Delete an attribute node: it can be deleted by removeattribute(attrname) or Removeattributenode (node) of the element node to which the attribute node belongs.

③ emptying text nodes: The simplest and most commonly used method is to set the Namenode property of the text node directly to the empty string: Textnode.nodevalue = "".

4) Creating and adding nodes

① Create nodes: element nodes and text nodes can be created individually through the createelement (elename), createTextNode (NodeValue) method of the Document object. The attribute node also has its own create method, but with less use, the attribute can be added directly using the SetAttribute () method of the element node.

② Add Nodes: Two important methods: AppendChild () and InsertBefore (), see Methods in Node Interface (section 13).

extension: the above two methods are used when the parent node is known, or you can add a new node directly after the sibling node: X.insertbefore (NewNode) and X.appendchild (NewNode) can append a new child node to the X.

5) Replace node: main Master ReplaceChild (NewNode, OldNode) Replace element node. (There are more simple methods for attribute nodes and text nodes)

18. HTML DOM (☆)

1) in the HTML DOM, the simplest way to get and change the contents of an element is to use the element's innerHTML property (the InnerText property returns the innerHTML with the label removed)

2) Change the HTML style (style property): Element.style.color = "Red";

3) DOM event: When the HTML element "Something happens", the browser generates an event, and the HTML DOM allows JS to respond to the HTML event. There are two ways to use it:

① add JavaScript code to the HTML event properties , such as OnClick = JavaScript

The ②html DOM allows you to assign an event to an HTML element in JS, as shown in the following code to assign the onclick event to the button element: document.getElementById ("mybtn"). onclick = function () {}

The common JS events are:

Load event: OnLoad

Mouse movement Events: onmouseover, onmouseout

Mouse Click event: onclick

Focus and Defocus events: onfocus, onblur

Keyboard events: onkeypress (typically used with Event.keycode)

Commit and Reset events: OnSubmit, OnReset

Domain Change event: onchange

19. Dom Operation exercises

Dom Operation Exercise Please read this blog another article: http://www.flyne.org/article/420

20. BOM and HTML DOM diagram (learn)

JavaScript (Core, BOM, DOM)

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.