JavaScript DOM Programming Art-Read notes

Source: Internet
Author: User

Statement
The code written by JavaScript must be embedded in a html/xhtml document to be executed.

<! DOCTYPE html>javascript goes here ... </script>Mark-upgoes here ... </body>

Better way to put JavaScript code in a separate file ——. js (extension)

<! DOCTYPE html>Mark-upgoes ... </body>


Example: test.html

<! DOCTYPE html>Mark-up Goes here ... </body>

Grammar
The syntax of the JavaScript language is very similar to the syntax of some programming languages such as Java and C + +.

Statement
Scripts written by JavaScript or any other programming language are made up of a series of instructions called statements (statement).
Good programming Habits:
First statement;
Second statement;

Comments
Do not want the JavaScript interpreter to actually execute such a statement. Called a comment (comment).
Some ideas and considerations for writing code can be documented for future reference and to track the execution of the code.
Single-line Comment:

// Note to Self:comments is good.


Multi-line Comments:

/* Note to self:comments art good */

Variable
Something that can change is called a variable (variable).
The operation of storing a value in a variable is called an Assignment (assinment).

These variables are assigned a syntax in javascript:

Mood == 33;

Pop-up Warning window:

alert (mood); alert (age);

Statement
JavaScript allows programmers to assign values directly to variables without having to declare them in advance (declare).
Make a statement:

var mood; var age;


JavaScript does not allow the names of variables to contain spaces or punctuation marks ($ exceptions).

Data type
There is no need to make a declaration, type declaration (typing) of the data type in a JavaScript script.
JavaScript is known as the weakly typed (weakly typed) language.
String

var mood = "Happy"; var mood = ' happy '; var mood = ' don\ ' t ask '; (\ character escapes escaping)

Numerical

var age = 33.25;

Boolean Value (Boolean)

var true ; var false;

Arrays (Array)
Each value in the collection is an element of this array.
Array[index] = element;

var beatles = Array (4); beatles[0] = "John"; beatles[1] = "Paul"; beatles[2] = "George "; beatles[3] =" Ringo ";
var beatles = Array ("John", "Paul", "George", "Ringo"); var beatles =["John", "Paul", "George", "Ringo"];
var beatles = Array (1990,3554,1244,6565);

Operation
Arithmetic operators

var year =; var message = "The year is"+ = year;alert (message);

Conditional statements
JavaScript scripts need to use conditional statements (conditional statement) to make judgments and decisions.
If statement

if (condition) {statement;}

Example

if(1>2) {alert ("The World has gone mad!" );} Else {alert ("All are well and the World");}

Comparison operators

= Assignment = = equals comparison! = Not equal to Comparison

Logical operator (operand)

&& logic and | | Logical OR! Logical non-

Looping statements
The IF statement is perhaps the most important and useful condition statement. Insufficient is not used to complete the repetitive operation.
While statement

 while (condition) {statement;}

Example

var count = 1;  while (Count < one) {alert (count); count+ +;}

Do...while statements

do while (condition);

Example

var count = 1;  Do {alert (count); count+ +;}  while (Count < 11);

Variant

var count = 1;  Do {alert (count); count++ while (count < 1);

For language

Initialize;  while (condition) {statements;increment;}


For loop

 for (initial condition; test condition; alter condition) {statement;}

Example

for (var count=1;count < 11; count++) {alert (count);}

Example

var beatles = Array ("John", "Paul", "George", "Ringo");  for (var count = 0; count < beatles.length; count++) {alert (Beatles[count]);}

Functions (function)
Make a definition of the function before calling them:

function shout () {var beatles = Array ("John", "Paul", "George", "Ringo");  for var count = 0; Count < Beatles.length; count++ ) {    alert (Beatles[count]);}}

Defines the syntax for a function:

function name (arguments) {statements;}

A function that passes two parameters:

function Multiplay (num1,num2) {var total = num1*num2;alert (total);}

In the script that defines the function, we can call the function from anywhere:

Multiply (10,2);

The function can not only receive data (in the form of parameters), but also return data. You need to use the return statement:

function Multiplay (num1,num2) {var total = num1*num2; return Total ;}

The function is just a parameter and returns a value:

function Converttocelsius (temp) {var result = temp-32= result/1.8; return result;}

The real value of a function can be useful as a data type, which means that we can assign a function's invocation result to a variable:

var = Temp_fahrenheit; var temp_celsius = Converttocelsius (temp_fahrenheit); alert (Temp_celsius);

The Fahrenheit temperature value of 95 is converted to Celsius temperature value: 35

Scope of the variable (scope)
Global variables (globals variable)
Locals (local variable)

Objects (object)
An object is a self-contained collection of data that can be accessed in two forms-property and method):
A property is a variable that is subordinate to a particular object;
A method is a function that knowledge can be called by a particular object.

In JavaScript scripts, properties and methods need to be accessed using the "point" syntax shown below:

Object.propertyObject.method ()

One, user-defined objects (User-defined object)
Create your own objects using the JavaScript language.
JavaScript provides a set of pre-defined objects that you can use directly in your own scripts, which are called built-in objects (native object).

Ii. built-in objects (native object)
Array arrays are JavaScript built-in objects. The Math object and the Date object are also built-in objects.
Create a new instance of the array object:
var beatles = new Array ();
Gets the number of elements in the array:
Beatles.length;

Math Object
var num = 7.651;
var num = math.round (num);
alert (num);

Date Object
The JavaScript interpreter automatically uses the current date and time:
var current_date = new Date ();
The Date object provides GetDay (), getHours (), and Getmouth (), which are used to retrieve various information about a particular date.
var today = Current_date.getday ();

Third, host objects (host object)
The predefined objects provided by the Web browser are called host objects (host object). Mainly includes form, image and element.

The Document object can also be used to obtain information about any one element on a given page.
Four very useful DOM methods:
getElementById
getElementsByTagName
GetAttribute
SetAttribute

DOM Document Object Model
D Documentation
O Object
M model

BOM (Window object model) Browser object models

Family Tree : Parent (father), child (son), sibling (brother)

Basic Page--shopping list

<! DOCTYPE html>t forget to buy this stuff.</p><ul id= "purchases" ><li>a tin of Beans</li><li>cheese </li><li>Milk</li></ul></body>

Nodes (node)
A document is a collection of nodes.

element node : P, ul .....
text node : The text contained within the element.
attribute nodes (attribute node): Title ...
CSS (cascading style sheets): Inheritance (inheritance)
Class Property: All elements have a class attribute, and different elements can have the same class attribute value.
ID attribute: Adds a unique identifier to an element in the Web page.

getElementById () method

document.getElementById (ID);

Example

document.getElementById ("purchases");

The getElementById () method returns an object that can be validated with the typeof operator.

<script type= "Text/javascript" >alert (typeof document.getElementById ("purchases")); </script>

getElementsByTagName () method
Element.getelementsbytagname (tag);
Example
document.getElementsByTagName ("Li");
The getElementsByTagName () method returns an array of objects, each corresponding to an element in the document that has a given label. is also a function with only one parameter.
<script type= "Text/javascript" >
Alert (document.getelementsbytagname ("Li"). length);
</script>
The method of iterating through the array using the loop and typeof operators is verified:
for (Var i=0; i< document.getelementsbytagname ("Li"). length; i++) {
Alert (typeof document.getelementsbytagname ("Li") [i]);
}
Assignment variables:
var items = document.getelementsbytagname ("Li");
for (var i=0; i < items.length; i++) {
Alert (typeof items[I]);
}

Gets the total number of ELEMENT nodes for a document:
Alert (document.getElementsByTagName ("*"). length);

Gets the id attribute of the purchase element that has the number of list items (LI) in the package:
var shopping = document.getElementById ("purchases");
var items = shopping.getelementsbytagname ("*");
The items array is exactly the same length as the number of list item elements in this document:
alert (items.length);
Prove that each value in the items array is indeed an object:
for (var i=0; i < items.length; i++) {
Alert (typeof items[I]);
}

A document is a tree of nodes.
Nodes are divided into different types: element nodes, attribute nodes, text nodes, and so on.
The getElementById () method returns an object that corresponds to a specific element node in the document.
The getElementsByTagName () method returns an array of objects that correspond to a specific element node in the document.
Each of these nodes is an object.

GetAttribute () method
is a function, it has only one parameter--the name of the property to be queried:
Objece.getattribute (attribute);
cannot be called through the Document object, only through an element node object.
Query the Title property of each P element:
var paras = document.getelementsbytagname ("P");
for (var i=0; i< paras.length; i++) {
Alert (paras[i].getattribute ("title"));
}
A message pops up only when the title property is present:
var paras = document.getelementsbytagname ("P");
for (var i=0; i< paras.length; i++) {
var title_text = Paras[i].getattribute ("title");
if (title_text! = null) {
alert (Title_text);
}
}
Simplified:
var paras = document.getelementsbytagname ("P");
for (var i=0; i< paras.length; i++) {
var title_text = Paras[i].getattribute ("title");
if (title_text) alert (title_text);
}

SetAttribute () method
Allows us to make modifications to the value of the attribute node.
Functions that can only be called through element node objects, but the setattribute () method requires that we pass two parameters to it:
Object.setattribute (Attribute,value);

Example: Retrieving the id attribute purchase, setting the Title property to a list of goods:
var shopping = document.getElementById ("purchases");
Shopping.setattribute ("title", "a list of goods");

The GetAttribute () method is used to prove that the value of the title property of this element has indeed changed:
var shopping = document.getElementById ("purchases");
Alert (Shopping.getattribute ("title"));
Shopping.setattribute ("title", "a list of goods");
Alert (Shopping.getattribute ("title"));

The P element has the title attribute and changes its current value through the SetAttribute () method:
var paras = document.getelementsbytagname ("P");
for (var i=0; i< paras.length; i++) {
var title_text = Paras[i].getattribute ("title");
if (Title_text) {
paras[I].setattribute ("title", "brand new title text");
Alert (paras[i].getattribute ("title"));
}
}

DOM works by loading the static content of the document and then dynamically refreshing it, and dynamic refresh does not affect the static content of the document.

Dom other properties and methods
NodeName
NodeValue
Chilenodes
NextSibling
ParentNode

Example: Creating a picture library with JavaScript and DOM
Thought
Write a good markup language document.
Write a JavaScript function to display the picture that the user wants to see.
Triggers a function that invokes the display of JavaScript images in markup language documents.
Extending the functionality of this JavaScript function requires several new DOM methods.

Writing Markup Language documents
<! DOCTYPE html>
<meta charset= "Utf-8";
<meta name= "Viewport" Content= "Width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" ><!--viewport label-->
< Title>image gallery</title>
<body>
< Ul>
<li>
<a href= "images/fireworks.jpg" title= "a fireworks display" ></A>
</li>
<li>
<a href= "images/fireworks.jpg" title= "a fireworks display" ></A>
</li>
<li>
<a href= "images/fireworks.jpg" title= "a fireworks display" ></A>
</li>
<li
<a href= "images/fireworks.jpg" title= "a fireworks display" ></A>
</li>
</ul>
</body>

Save this document as a gallery.html file and save the image in the subdirectory images.
When clicking on a link, stay on this page instead of going to another window.
When you click on a link, you'll see the picture and the original picture list on this page.
There are several improvements that need to be made:
By adding a "placeholder" image, you can reserve a browse area for the picture on this home page.
When you click on a link, the default behavior of the page is blocked.
When you click a link, the placeholder image is replaced with the picture that corresponds to that link.

Replace the "placeholder" image with the src attribute by changing it to the one you want to see:
function Showpic (whichpic)
Whichpic.getattribute ("href");
var Source = Whichpic.getattribute ("href");
document.getElementById ("placeholder");
var placeholder = document.getElementById ("placeholder");
Placeholder.setattribute ("src", source);
document.getElementById ("placeholder"). SetAttribute ("src", Whichpic.getattribute ("href"));

JavaScript DOM Programming Art-Read notes

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.