Javascriptx learning Summary

Source: Internet
Author: User
Tags array definition

Javascriptx learning Summary
JavaScript learning Summary




Chapter 1 Understanding JavaScript


1. What is JavaScript?
JavaScript is a programming language that can be used to add interactivity to webpages.
Scripting language)
<Script> </script> label
Included in the HTML page (usually in the Stored in an external file <script src = "external file name">


2. Differences between Java and Javascript
The difference between Java and Javascript is like the difference between India and Indonesia. The name is a bit the same.


3. About Ajax
Ajax (Asynchronous Javascript XML) Asynchronous JavaScript and XML: A web development technology used to create interactive web applications.
Including Technology
XHTML
CSS
Use JavaScript to access DOM
XML
XMLHttpRequest


4. JavaScript and object-oriented
Objects, attributes, and methods are combined: node number syntax ()
Document. getElementById ('div1 '). style. display


5. Handle events
Event: The operation performed by the user when accessing the page.
For example:
When the mouse moves in, the display attribute value is block; when the mouse moves out, the dispay attribute value is none.
Onmouseover = "document. getElementById ('div1 '). style. display = 'block'; "onmouseout =" document. getElementById ('div1 '). style. display = 'none ';"
Div and span: ID range
Div: block-level element with a line break around the element
Span: the element in the row. It does not wrap the line before or after it.
Difference between class and id Selector
The class style can be used multiple times, and the id style can only be used once. The priority of the id selector is higher than that of the category selector.


6. Values and variables
Typeof detection variable type
Usage: alert (typeof );
Undefined type: undefined; or, it is defined but not assigned a value.
What is Object?
Simple Explanation: Not a basic type, it is a composite type. Except number (integer, real number), string, boolean, undefined, all others are objects.
Note:
JavaScript is case sensitive.
Variable value: weak JavaScript type. Standard: a variable should store only one type of data.
=: Convert the items on both sides to the same type before comparison (implicit type conversion)
===: No conversion, direct comparison
Addition: String join and numeric addition. The first type is preferred.
Naming rules and necessity
Readability-understandable
Normative-compliant with the rules (letters, numbers, underscores, $, cannot begin with a number)
Hungarian naming convention
Type prefix
Uppercase letters
For example, alert (parseInt (n/60) + 'mine' + n % 60 + 'second'); parseInt converts a string to an integer
Value assignment: =, + =,-=, * =,/=, % =
Link: <,>, <=,> = ,! = ,! =
Logic: &, | or ,! No
Operator priority: parentheses


7. structure, performance, and behavior (this is the core)
Separation of structure, performance, and Behavior
HTML (structure): contains the content and structure of the page
CSS: controls the appearance and performance of a page.
JavaScript (behavior): Controls page Behavior


Example:
Use a CSS style sheet on the page
<Link id = "link1" href = "css1.css" rel = "stylesheet" type = "text/css"/>
Click Event: onclick
Onclick = "document.getelementbyid('link1'{.href}'css1.css ';"
Separate the behavior (place the JS Code in the tag and between lines, the Code is not readable, and the modification workload is too large .)
Window. onload = function (){
Var oBtn1 = document. getElementById ('btn1 ');
OBtn1.onclick = function (){
Document.getelementbyid('link1'{.href}'css1.css ';
}

Var oBtn2 = document. getElementById ('btn2 ');
OBtn2.onclick = function (){
Document.getelementbyid('link1'{.href}'css2.css ';
}
}
Write JavaScript code in the. js File
<Script src = "changeskin. js"/>
Supplement:
Value
Alert (oTxt1.value + oTxt2.value );
Information about NaN: NaN not a number
Var a = parseInt ('abc ');
Var B = parseInt ('aaa ');
Alert (a = NaN); // false
Alert (a = B); // false
Processing: isNaN () function
Var a = parseInt ('abc ');
Alert (isNaN (a); // true
Variable Scope)
Local variable: used only in this function.
Global variables: they are not defined in any function and can be used anywhere (do not use global variables whenever possible)
What is a closure?
Sub-functions can use local variables in the parent function.
Example: The color of the line (aLi is equivalent to an array, aLi. length indicates the number of elements in the array)


Example:
<Script>
Window. onload = function (){
Var oUl = document. getElementById ('ul1 ');
Var aLi = oUl. getElementsByTagName ('lil ');
Var I = 0;
For (I = 0; I <aLi. length; I ++ ){
If (I % 2 = 0) {// 0, 2, 4, 6, 8, 10...
ALi [I]. style. background = '# CCC ';
}
}
};
</Script>
</Head>?
<Body>
<Ul id = "ul1">
<Li> </li>
<Li> </li>
<Li> </li>
<Li> </li>
<Li> </li>
<Li> </li>
<Li> </li>
</Ul>
</Body>


The summary is as follows:
Composition of js:
ECMAScript
DOM: Operation Document (page)
BOM: Operation window


About variables:
Var
Typeof (): number, string, boolean, object, undefined, null, function


Calculation:
Implicit: = ,-
Explicit: parseInt/NaN
==/===


Events:
Onmouseover/onmouseout/onclick
Event processing is not implemented between lines
Window. onload = function (){...}
Element name. event name = function (){...}


Element:
GetElementById (element id name)
GetElementsByTagName ("") by Tag name-> Array
Array. length


About Arrays:
Array. sort ()
String. split (resolution separator)
Array. join (connector between elements)


Style:
Style. display = block/none
Style. background = color
Check box. checked = true/false




Separation of structure, performance, and behavior:
1. layout --- html
2. Style --- <link href = ""> (.css)
<Style>


</Style>
3. js
<Script> </script> (<Script src = ""> (. js)



Convert text to numbers
ParseInt
ParseFloat


Principle: starts from the leftmost character and ends with the first character that is not a number (it can be converted even if the text contains a non-number)


If the conversion fails, a NaN is returned.


Method for judging NaN: Use the isNaN () function






Chapter 2: program flow control, array, Function


1. What is true or false:
True: true, non-zero number, non-empty string, non-empty object
False: false, number zero, empty string, empty object, undefined


2. Branch
If
Switch
? :


3. Loop
While
For
Do-while
For... In: used to enumerate the attributes of an object.


Example:
<Script type = "text/javascript">
Window. onload = function (){
Var oBtn = document. getElementById ('btn ');
Var aInput = document. getElementsByTagName ('input'); // obtain the element by Tag Name
?
OBtn. onclick = function (){
// Alert (aInput. length );
For (var I = 0; I <aInput. length; I ++)
AInput [I]. checked = true;
}
};
</Script>


4, array
Array Definition
Use the Array keyword to define
Example: var arr = new Array ();
Var arr = new Array (1, 2, 3, 4 );
Use [] to define
Example: var arr = [1, 2, 4]
Attribute of the array
Array length: length attribute


Array Method
Push: add elements to the end of the array
Pop: a data is popped up from the end of the array.
Shift: deletes an element from the array header.
Unshift: add an element to the array Header
Sort: Sorting
Sort rules: Sort strings in alphabetical order
Comparison Functions
Concat: connects two Arrays
Split: the parsed string is an array.
Join: delimiter between elements when the array is output


Example:
Sort arrays from small to large
<Script type = "text/javascript">
Var arr = [96, 8, 12, 72, 33,118];


Arr. sort (function (num1, num2 ){
Return num1-num2;
});


Alert (arr );
</Script>


5. Functions
Function return value
No return/return;: undefined
Rule: Make a function return only one type of value.
Function Parameters
Common parameters:
Parameter type
Number of parameters
Arguments: parameter array, variable parameter, indefinite parameter
Example:
<Script type = "text/javascript">
Function show (){
Alert (arguments [1]);
}
Show (12, 5 );
</Script>
The above will show 5, the 2nd elements in the array


Example:
Simulate handling of "overload"
<Script type = "text/javascript">
Function sum (){
Var result = 0;
Var I = 0;

For (I = 0; I <arguments. length; I ++ ){
Result + = arguments [I];
}

Alert (result );
}
Sum (12, 5, 7, 8, 12, 5, 7, 8, 12, 5, 7, 8, 12, 12, 5, 7, 8, 12, 5, 7, 8, 12, 5, 7, 8, 12, 5, 7, 8, 12 );
</Script>


6. CSS Functions
Css ('background ')
Css ('background', 'red ');




Chapter 3 DOM (Ducument Object Model)


1. Get nodes
GetElementById
Get subnode: childNodes
Number of subnodes
Operate subnodes
Example:
Window. onload = function (){
Var oUl = document. getElementById ('ul1 ');

OUl. childNodes [0]. style. background = yellow'; // The first subnode of ul, that is, the following li
}


2. Check the node type.
NodeType
Element Node: 1
Text node: 3
Attribute node: 2
Example:
<Script type = "text/javascript">
Window. onload = function (){
Alert (document. body. childNodes [1]. nodeType );
}
</Script>


3. parent node parentNode
The parent node has only one


Example: hide a parent node
Window. onload = function (){
Var aA = document. getElementsByTagName ('A ');
Var I = 0;

For (I = 0; I <aA. length; I ++ ){
AA [I]. onclick = function (){
This. parentNode. style. display = 'none ';
}
}
}
This: indicates the object that calls this method or attribute.


4, offsetParent
Obtains the parent node used to locate the current element.


5. subnodes
FirstChild, firstElementChild
LastChild, lastElementChild


Example:
Window. onload = function (){
Var oUl = document. getElementById ('ul1 ');

// Earlier version of IE
// OUl. firstChild. style. background = 'red ';

// FF, IE11
// OUl. firstElementChild. style. background = 'red ';

Var oFirst = oUl. firstElementChild | oUl. firstChild;

OFirst. style. background = 'red ';
}


6. DOM element search
Select element with id
Use tagName to select an element
Use className to select elements
Select all elements
Filter by using if
Encapsulated as a function
Function getByClass (oParent, sClass ){
Var aEle = oParent. getElementsByTagName ('*');
Var aResult = []; // There may be multiple, placed in the array
Var I = 0;

For (I = 0; I <aEle. length; I ++ ){
If (aEle [I]. className = sClass ){
AResult. push (aEle [I]);
}
}
Return aResult;
}
Window. onload = function (){
Var oUl = document. getElementById ('ul1 ');
Var aBox = getByClass (oUl, 'box ');
Var I = 0;

For (I = 0; I <aBox. length; I ++ ){
ABox [I]. style. background = 'yellow ';
}
}


7. Create, insert, and delete Elements
Create DOM elements
CreateElement (Label name) creates a node
AppendChild (node)
Append a node
Example: insert li for ul
Window. onload = function (){
Var oBtn = document. getElementById ('tn1 ');
Var oTxt = document. getElementById ('txt1 ');
Var oUl = document. getElementById ('ul1 ');
OBtn. onclick = function (){
Var oLi = document. createElement ('lil ');
OLi. innerHTML = oTxt. value;
OUl. appendChild (oLi );
}
}
InnerHTML is something inside a tag.
<Div id = "div1">
Here is something inside the tag, which is stored in innerHTML



Insert element
InsertBefore (node, original node) is inserted before existing elements
Example: insert li in reverse order
Window. onload = function (){
Var oBtn = document. getElementById ('tn1 ');
Var oTxt = document. getElementById ('txt1 ');
Var oUl = document. getElementById ('ul1 ');
OBtn. onclick = function (){
Var oLi = document. createElement ('lil ');
Var aLi = oUl. getElementsByTagName ('lil ');
OLi. innerHTML = oTxt. value;
If (aLi. length = 0 ){
OUl. appendChild (oLi );
}
Else {
OUl. insertBefore (oLi, aLi [0]);
}
}
}




Delete DOM elements
RemoveChild (node) deletes a node
Example: delete li
Window. onload = function (){
Var aA = document. getElementsByTagName ('A ');
Var oUl = document. getElementById ('ul1 ');
Var I = 0;
For (I = 0; I <aA. length; I ++ ){
AA [I]. onclick = function (){
OUl. removeChild (this. parentNode );
}
}
}




Course 4 handles events


1. Add events to the document
Document. onclick = function (){
Alert ('A ');
}


2. Obtain click coordinates from the event object (considering the compatibility of different browsers)
Document. onclick = function (ev ){
If (ev ){
Alert (ev. clientX + "," + ev. clientY );
} Else {
Alert (event. clientX + "," + event. clientY );
}
}


3, or operation
Non-0 --- true 0/null/false
12 | false 12
0 | 'abc'
''| True
12 | 0 12
12 | null 12
Null | 'abc'
'Abc' | 12 'abc'
Browser compatibility using or computing
Document. onclick = function (ev ){
Var oEvent = ev | event; // put the special one in front

Alert (oEvent. clientX + ',' + oEvent. clientY );
};


4. event stream
Events are upgraded from the bottom layer of the DOM hierarchy like bubbles.
Event Processing: Avoid interference caused by event bubbles
Window. onload = function (){
Var oBtn = document. getElementById ('tn1 ');
Var oDiv = document. getElementById ('div1 ');

OBtn. onclick = function (ev ){
Var oEvent = ev | event;
ODiv. style. display = 'block ';

OEvent. cancelBubble = true; // prevents bubbling.
};

Document. onclick = function (){
ODiv. style. display = 'none ';
};
};


5. mouse events
Mouse position
Document. onmousemove = function (ev)
{
Var oEvent = ev | event;
Var oDiv = document. getElementById ('div1 ');

ODiv. style. left = oEvent. clientX + 'px ';
ODiv. style. top = oEvent. clientY + 'px ';
};


Scroll position
Mouse follow improvement:
Document. onmousemove = function (ev ){
Var oEvent = ev | event;
Var oDiv = document. getElementById ('div1 ');
Var scrollTop upload document.doc umentElement. scrollTop | document. body. scrollTop;
Var scrollleft;document.doc umentElement. scrollLeft | document. body. scrollLeft;


ODiv. style. left = oEvent. clientX + scrollLeft + 'px'; // perform horizontal scrolling.
ODiv. style. top = oEvent. clientY + scrollTop + 'px'; // perform vertical scrolling.
};


6. Keyboard Events
Compare mouse events: onclick = onmousedown + onmouseup
Keyboard event: onpress = onkeydown + onkeyup
Keycode
Document. onkeydown = function (ev ){
Var oEvent = ev | event;

Alert (oEvent. keyCode );
}


OffsetWidth: div width
Border: 1px; +
Padding (padding): 10px +
Margin (outer margin): 20px-
OffsetLeft: left margin of the div
OffsetTop
OffsetRight


Keyboard control movement: Move Up, down, left, right
Document. onkeydown = function (ev ){
Var oEvent = ev | event;
Var oDiv = document. getElementById ('div1 ');


If (oEvent. keyCode = 37) {// left
ODiv. style. left = oDiv. offsetLeft-10 + 'px ';
} Else if (oEvent. keyCode = 39 ){
ODiv. style. left = oDiv. offsetLeft + 10 + 'px ';
} Else if (oEvent. keyCode = 38 ){
ODiv. style. left = oDiv. offsetTop-10 + 'px ';
} Else if (oEvent. keyCode = 40 ){
ODiv. style. left = oDiv. offsetTop + 10 + 'px ';
}
};


Click the message with the mouse:
Window. onload = function (){
Var oBtn = document. getElementById ('tn1 ');
Var oTxt1 = document. getElementById ('txt1 ');
Var oTxt2 = document. getElementById ('txt2 ');

OBtn. onclick = function (){
OTxt1.value + = oTxt2.value + '\ n ';
OTxt2.value = '';
};
};


Enter key message:
Window. onload = function (){
......


OTxt2.onkeydown = function (ev) {// pay attention to the object with the event added
Var oEvent = ev | event;

If (oEvent. keyCode = 13 ){
OTxt1.value + = oTxt2.value + '\ n ';
OTxt2.value = '';
}
};
};


Ctrl + enter submit:
Window. onload = function (){
......


OTxt2.onkeydown = function (ev) {// pay attention to the object with the event added
Var oEvent = ev | event;

If (oEvent. ctrlKey & oEvent. keyCode = 13 ){
OTxt1.value + = oTxt2.value + '\ n ';
OTxt2.value = '';
}
};
};


7. default behavior


What is default behavior?
You do not need to write your own functions.
Right-click the shortcut menu (oncontextmenu event (context menu): Right-click the menu)
Text Box Input
Form submission
The general method to prevent default behaviors: return false


Right-click the custom menu:
Document. oncontextmenu = function (ev ){
Var oEvent = ev | event;
Var oUl = document. getElementById ('ul1 ');
Var scrollTop upload document.doc umentElement. scrollTop | document. body. scrollTop;
Var scrollleft;document.doc umentElement. scrollLeft | document. body. scrollLeft;


OUl. style. display = 'block ';
OUl. style. left = oEvent. clientX + scrollLeft + 'px ';;
OUl. style. top = oEvent. clientY + scrollTop + 'px;

Return false; // The context menu of the blocked System
};


Right-click the custom menu:
Document. onclick = function (){
Var oUl = document. getElementById ('ul1 ');
OUl. style. display = 'none ';
};


8. Drag
Onmousedown: storage distance
Onmousemove: calculates the latest position of the DIV based on the distance.


<Script>
Window. onload = function ()
{
Var oDiv = document. getElementById ('div1 ');

Var disX = 0;
Var disY = 0;

ODiv. onmousedown = function (ev)
{
Var oEvent = ev | event;

DisX = oEvent. clientX-oDiv.offsetLeft;
DisY = oEvent. clientY-oDiv.offsetTop;

Document. onmousemove = function (ev) // place it under the onmousedown event to prevent the mouse from moving out
{
Var oEvent = ev | event;
Var l = oEvent. clientX-disX;
Var t = oEvent. clientY-disY;

If (l <0)
{
L = 0;
}
Else if (l> document.doc umentElement. clientWidth-oDiv.offsetWidth)
{
Lw.document.doc umentElement. clientWidth-oDiv.offsetWidth;
}

If (t <0)
{
T = 0;
}
Else if (t> document.doc umentElement. clientHeight-oDiv.offsetHeight)
{
Tsf-document.doc umentElement. clientHeight-oDiv.offsetHeight;
}

ODiv. style. left = l + 'px ';
ODiv. style. top = t + 'px ';
};

Document. onmouseup = function ()
{
Document. onmousemove = null;
Document. onmouseup = null;
};

Return false;
};
};
</Script>


Conclusion:
1. event object-pay attention to compatibility
Function (ev)
Var oEvent = ev | event;




2. event stream
Parent node. The child node has the same event.
OEvent. cancelBubble = true; prevents event bubbles


3. mouse events


Mouse Click position:
OEvent. clientX left margin of the mouse from the visible area
OEvent. clientY margin between the mouse and the visible area


Scroll position with a scroll bar (note compatibility ):
Var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft;
Var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop;


Div positioning: oDiv. style. left = scrollLeft + oEvent. clientX + 'px ';
ODiv. style. top = scrollTop + oEvent. clientY + 'px ';


4. Keyboard Events
OEvent. keyCode
Value: Test


Common Values: 13 -- press ENTER




5th course BOM


1. Open the window
Window. open (page address, open mode );
Open Method: In which frame does it open?
_ Blank: new window, default
_ Self: current window
Example:
OBtn. onclick = function (){
Window. open ('www.126.com/',' _ self ');
};
Run the Code:
Document. write (): Output content to the page


Example: document. write ('aaa ');
Run and view the page source code
Window. onload = function (){
Var oTxt = document. getElementById ('txt1 ');
Var oBtn = document. getElementById ('tn1 ');

OBtn. onclick = function (){
Var oNewWin = window. open ('about: blank ');
ONewWin.doc ument. write (oTxt. value );
};
};
<Body>
<Textarea id = "txt1" rows = "10" cols = "40"> </textarea>

<Input id = "btn1" type = "button" value = "run"/>
</Body>


2. Close the window.
Window. close ()
Window. onload = function (){
Var oBtn = document. getElementById ('tn1 ');

OBtn. onclick = function (){
Window. close ();
};
};


<Body>
<Input id = "btn1" type = "button" value = "close"/>
</Body>


3. common attributes
Window. navigator. userAgent: browser version number
Window. location: Current page address
Read
Alert (window. location );
Write
Window. location = 'HTTP: // www.126.com /'


4. System Dialog
Var B = confirm ('Is it raining today? ');
Alert (B );
Var str = prompt ('enter your name', 'song ');
Alert (str );


5. Dimensions and coordinates
Visible area size
Document.doc umentElement. clientWidth
Document.doc umentElement. clientHeight
Scroll distance
Document. body. scrollTop
Document.doc umentElement. scrollTop


Sidebar example:
Window. onscroll = function (){
Var oDiv = document. getElementById ('div1 ');
Var scrollTop=document.doc umentElement. scrollTop | document. body. scrollTop;
Var t=(document.doc umentElement. clientHeight-oDiv.offsetHeight)/2;

ODiv. style. top = scrollTop + t + 'px ';
};
<Style>
# Div1 {width: 100px; height: 100px; background: red; position: absolute; right: 0 ;}
</Style>


Problems to be Solved
Page just loaded
Page size change
Window. onresize = window. onload = ...... Connect to the face, so that you can center and right

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.