JavaScript (i)

Source: Internet
Author: User
Tags script tag tag name



Introduction to JavaScript

JavaScript is a client-side scripting language that is Object-and event-driven and has relative security, is a dynamic, weakly-typed, prototype-based language with built-in support classes. Its interpreter is called the JavaScript engine, which is part of the browser. It is also a scripting language widely used in client Web development. Originally designed by Netscape (Netscape) Brandon Aick (Brendan Eich), in 1997, in coordination with the ECMA (European Association of Computer Manufacturers), a working group comprising Netscape, Sun, Microsoft, and Borland determined Unified Standard: ECMA-262. JavaScript is a registered trademark of Sun Corporation and is not directly related to Java.

JavaScript Basic Features

>javascript is a lightweight programming language.

>javascript is a programmatic code that can be inserted into an HTML page.

>javascript is inserted into the HTML page and can be performed by all modern browsers.

>javascript is easy to learn.

start the JavaScript learning Journey

The starting point for learning JavaScript is working with Web pages, so let's start with the basic syntax and how to use the DOM for simple operations. Let's look at a simple code.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-type" Content="text/html; Charset=utf-8 "/><title>My Javascrip</title></head><body><button>Click me!</button> <script type="Text/javascript"> //With the Window.onload event, after the document is loaded, the relevant operation window.onload =  function(){//   Gets the button corresponding to the element node object  var btn = document.getElementsByTagName ("button") [0]; //Bind order hit response function Btn.onclick = function  (){//Print text value alert (t       his. Firstchild.nodevalue); }   }                               </script> </body></html>




Four questions from the above simple application

1. What is the difference between JavaScript basic syntax and Java?
2. Why use Window.onload?
3. How do I get my program to do what I want after I click the button?
4. How does the button label in the HTML code be represented in the JavaScript code? How do I get it?

JavaScript Basic Syntax

1.script Tags:

> < script> tags are used to define client-side scripts, such as JavaScript;

> syntactically, < script> tags can be written anywhere in the < html>
The >type property is required to specify the MIME type of the script. For JavaScript, the MIME type is "Text/javascript".

> Language properties: Not recommended.

> inserting JavaScript code directly into the document

<script type="text/javascript">alert("Hello World!"); </script>

Use the < script> tag to insert JavaScript code in an HTML page. Note that the < script> label should appear in pairs and write the JavaScript code between < script></script>.



> Connecting external JavaScript files
Use the SRC attribute of the < script> tag: Specifies the URL of the external script file.
Pure JavaScript code can be saved to the ". js" file, in the ". js" file, write the JavaScript code and in the script tag exactly the same

<script type="text/javascript" src="script/jquery-1.7.2.js"></script>

Note: Loading an external CSS style sheet uses a link tag, and loading an external JS file is different!

 <link rel="stylesheet"type="text/css" href="theme.css"


2. JavaScript Data Type

string: There is no "character" data in JavaScript, and a single character is treated as a string.
Digital Type: JavaScript does not differentiate between integral and floating-point types, and all numbers are represented by floating-point types.
Boolean type:True for true, nonzero number, non-empty string, False for false, number 0, empty string, undefined, null.
function:In JavaScript, a function is also an object that can be assigned as a value to a variable, and the function name is a reference to that object.
Null:Represents "empty". Null is a data type, it has only one value: null does not represent a numeric type of 0, does not represent the string type "" "empty string is not a valid number, string, object, array and function, what data type is not JavaScript case-sensitive, NULL, NULL is not equal to Null typeof (NULL) returns Object (for backwards compatibility).
undefined:Indicates that a variable is undefined but not assigned using an undefined variable that uses a property of an object that does not exist.

3. Variables

> Using the var keyword statement;

>javascript is a weakly typed language, and when declaring a variable, you do not need to specify a type. Variables can also store various types of data in use.

4. Functions



5. JavaScript is strictly case sensitive.

6. JavaScript identifier naming specification and Java completely oneSample.

where the JavaScript code should be written

JavaScript can be placed anywhere in the HTML page as a scripting language, but the browser interprets the HTML in order, so the preceding script is executed first. For example, the page display initialization of JS must be placed in the head, because the initialization is required to advance (such as the page body set CSS, etc.), and if the function is executed through the event call the position is not required.

We can place JavaScript code anywhere in the HTML file, but we usually place it in the head or body of the page.
Put in the < head> section
The most common way is to place the < script> element in the head section of the page, and the browser parses the head section to execute the code before parsing the rest of the page.
Put in the < body> section
The JavaScript code executes when the page reads to the statement.



the pros and cons of being put in different places

inside the HTML tag
< button onclick= "alert (' Hello ')" >ClickMe</button>
JS and HTML strong coupling, not conducive to the maintenance of code. For example: Bind the same click Response function to the 10 button buttons. If you want to modify a function name, you must modify it at the 10 button labels, which can cause omission or inconsistency.

< head> in tag
This location is more customary, but there is a serious problem: code executed before the body node cannot get directly inside the body node. Cause: The HTML document tree has not been loaded yet, more precisely-the DOM structure in memory is incomplete, not including the DOM nodes that are not loaded, so the associated node JavaScript program is not getting it.
Browser Loading principle Analysis
The browser downloads the HTML document in order from top to bottom, loads it into memory while downloading it, and then loads it all into memory. In addition, the drawing of the DOM tree structure takes precedence over the loading of the associated elements, compared to slices.
① is loaded and executed immediately after loading.
② will block subsequent content on the page (including rendering of the page, download of other resources).
When the browser loads the HTML document, it will stop loading the subsequent elements if it encounters the < script> tag, parsing and executing the JavaScript script file first.

< body> tag behind
Can get to the element node within the body,
Writing the code in this position is a serious non-conforming habit.

window.onload
The Window.onload event is triggered after the current document is fully loaded, and the HTML document tree is loaded and can be retrieved to any node in the current document.

The final load execution order:
-the browser loads the HTML document;
-encountered < script> tag stop loading behind HTML element, start parsing execution JavaScript code;
-Binds the response function that encapsulates the related operation to the Window.onload event;
-Load HTML elements, draw DOM structure
-HTML document loading complete, triggering window.onload events;
-Start executing the JavaScript code in the Window.onload event response function.

monitoring and responding to events

The listener and response of an event is the way the user interacts with the application.

To bind a control to an event response function step:
-Gets the control object from the Document object model;
-Declare an event response function;
-Assigns a reference to the event response function to the OnClick property of the control object

function(){   //从文档对象模型中获取控件对象   var btn = document.getElementsByTagName("button")[0];   //将事件响应函数的引用赋值给控件对象的 onclick 属性  function(){     varthis.firstChild.nodeValue;     alert(text);  }}


Suppress control default behavior

> Hyperlink jump function: return false;

> Submit button's Submit function: return false;

Event Bubbling

> Concept: The action of a user action is passed to the current control, and after the response function is executed, it continues to be passed to its parent element and is passed up until the top level.

> Cause: The overlap of the listening area.

> Cancel method: Return False.

Focus

> Gets the focus when a control is activated, or vice versa: Activated when a control gets focus

> Get Focus Event: onfocus

> Lost Focus Event: onblur

DOM

>document Object Model: Document object models define a standard way to access and manipulate HTML documents. is a unified standard developed by World wide international organizations, in many computer languages have different implementations such as C #, PHP, Java, Ruby, Perl, Python and so on.

>dom Tree
Parent-child relationship on top and bottom;
Left and right for brotherly relations.



> Node

The concept of node originates from the network theory and represents a connection point in the network. A network is a collection of nodes. Accordingly, we can say that the HTML document is a collection of DOM nodes;

Classification of nodes:

    • ELEMENT node: The most basic HTML element of the HTML document, corresponding to the HTML tag in the HTML document;
    • Attribute node: the attribute of the corresponding element;
    • Text node: Corresponds to the text content within the HTML tag.


Node Fine solution

Properties of the > Node

    • NodeName: Represents the name of the current node, read-only property. If the given node is a text node, the NodeName property returns a string that contains #text;
    • NodeType: Returns an integer that represents the type of the given node, the read-only attribute. -element node,--Attribute node, 3– text node
    • NodeValue: Returns the current value (string) of the given node. Read-write properties.
      Element node, return value is null
      Attribute node: The return value is the value of this property
      Text node: The return value is the content of this text node


> Get Element node

    • Obtained from the ID property value: Invokes the getElementById (id attribute of the Element) of the document object, and returns a reference to the current element node;
    • Gets the element node according to the tag name: invokes the getElementsByTagName (signature) of the Document object, returns an array of element nodes corresponding to the tag name, or invokes getElementsByTagName (labeled signature) from an element node Method.
    • Gets a set of element nodes based on the value of the Name property: Returns an array of elements by invoking the Getelementsbyname (the element's Name property value) method of the Document object, or if the HTML tag itself does not have a name attribute, by Getelem Entsbyname () method gets the element node, IE can not get to, strictly abide by the standards of the browser to obtain.
    • Operation Properties: The recommended method is to read with Element.attrname, write with element.attrname= "new value"; The classic method is to get an attribute node object using Element.getattributenode (property name) to return a reference to an attribute node object, read the value with Attrnode.nodevalue, modify the value with Attrnode.nodevalue = "New Value


> Get child nodes of an element node

    • See if the element node has child nodes: HasChildNodes (). Only element nodes may have child nodes.
    • Gets all child nodes through the ChildNodes property. IE and the standard of the Internet is different: IE ignores space (blank line), the standard will be the space also as a child node.
    • Gets the first child node of an element node through the FirstChild property. This method is often used to get text nodes such as: Element Node objects. FirstChild. If you want to get the text value: Element Node object. Firstchild.nodevalue.
    • Call the parent node's getElementsByTagName (), more targeted


> Creating Nodes

    • Note: Newly created nodes, including text nodes and element nodes, are not automatically added to the current document.
    • Create a text node document.createTextNode (text value) method that returns a reference to a text node var textnode = document.createTextNode ("Guangzhou");
    • Create an element node Document.createelement (sign) method that returns a reference to a new element node var Liele = document.createelement ("Li");
    • Adds the newly created text node to the element node within the elements node. appendchild (Text node)
liEle.appendChild(textNode);  alert(liEle.firstChild.nodeValue);var cityEle = document.getElementById("city"); 
    • Adds a newly created element node to the specified element node in the document. appendchild (newly created element node)
      Cityele.appendchild (Liele);


> Replace node: invokes the parent node. ReplaceChild (new node, target node) method to implement node substitution.

> Gets the parent node of the element node: child node. parentnode

> Copy node: The original element node. CloneNode (True) parameter is a Boolean value: True includes child nodes are copied, false only the current node (default).

> Inserting nodes

    • Adds a newly created element node to the document in front of the specified element node;
    • Parent node. insertbefore (new node, target node);
    • Custom Inserafter () function
function  insertafter   (Newnode,targetnode)  {  //adds a new node to the back of the target node  var  parentnode = Ta    Rgetnode.parentnode;  //determine if the target node is the last child node  if  (TargetNode = = Parentnode.lastchild)   {//if yes, the appendchild  parentnode.appendchild (NewNode) of the parent node; } else  {//if not, get the sibling node behind it  var  sibling = targetnode.nextsibling; //calls the parent node's InsertBefore method to sibling as the new target node  parentnode.insertbefore (NewNode,     Sibling); }  } 


> Delete node: element node. removechild (the child node to be deleted).

The >innerhtml property is read-write: reads the HTML code in the specified element node, writes: The HTML code is written to the start and end tags of the specified element node.

>nextsibling: Element node. nextSibling returns the next sibling element of the element node.

>previoussibling: Element node. previoussibling returns the previous sibling element of the element node.

JavaScript (i)

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.