###JavaScript
- Role: add dynamic effects and dynamic data to a page, html page is responsible for building the structure and content, css landscaping page
### JS history
In 1995 (NetScape) issued by the company Netscape, LiveScript, the same year was renamed JavaScript, Java language and have nothing, in order to heat rub
### JS Features
- Belong to a scripting language, does not require compiled, interpreted by the browser execution
- js language that can be embedded in html page
- js object-oriented language
- js are weakly typed languages
- Interactive high
- Safe js language can only access a variety of data in the browser, the browser can not be accessed outside of the data
introduced way ### JS language
- Inline: add js code in the event attribute of the element, js code is executed when the event occurs
- Inside: add html page
- Value type number
- String type string
- Boolean value type boolean
- Undefined undefined type
- Custom type object
Variable declaration and assignment ####
- js belonging to a weakly typed language
- java: int x = 10;
- js: var x = 10; was p = "abc"; was B = True / False;
#### common type of presentation
- Numeric types
- js are numerical values underlying type float, integer or decimal conversion automatically during use
Java int int. 5 X = Y = Z = 2 int X / Y; Z = 2
js var X = Y = 2. 5 var var z = x / y; z = 2.5 - NaN: Not a Number is not a number, for determining whether a variable is numeric type, use isNaN (variables) for determining isNaN (X) is the return value of true or false, true not representative number is representative of the number of false
- Boolean type
var b = true / false; - String
var S = "ABC";
var S = 'ABC'; - Undefined undefined type
- In the case where only a variable declaration is not assigned, then this variable is untyped
implicit conversion between types ###
- Numeric types
- String transfer: directly to 24-> "24"
- Boolean turn: 0 and NaN turn transformed into other false to true
- Boolean value type
- String transfer: directly to true -> "true" "abc" + true
- Numerical rotation: true-> 1 false-> 0 18 + true = 19
- String type
- Numerical rotation: can not turn around to go directly NaN
adder value will turn the string "20" + 5 = "205"
Save multiplication and division will turn into a string value of "20" = 15 -5
, any number and any NaN result of the operation is NaN - Boolean turn: other false true empty string transfer
- Undefined undefined
- Transfer values: NaN
- String transfer: Direct transfer "abc" + undefined "abcundefined"
- Turn Boolean: false if (undefined) {alert ( "aaa")}
- null
- Turn Value: 0
- Turn Boolean value: false
- String transfer: Direct transfer "ABC" = + null "abcnull"
#### operators + - * /% => <> = <= = ==! - And much the same Java
- with=: == first unified type === comparison value and then comparing the first type if the type of relatively equal value again
- Division will automatically convert the integer and fractional
- typeof x; typeof 66 + 6 = “number6”
***####语句 if else while do while for switch case - And much the same Java ***
- difference:
- If and while the contents inside the parentheses if not implicit Boolean automatically converted to Boolean
- int i for loop does not support the enhanced changed var i (new) for loop
#### method declaration
- java: public void method name (parameter list) {} method thereof
- js: function method name (parameter list) {} method thereof
- four common methods:
- No reference None Return Value
- There are no parameters return value
- There is no return value parameter
- There are parameters and return values
- three kinds of method declarations format:
- Method function name (parameter list) {} method thereof
- Method var name = function (parameter list) {} method body;
- Method var name = new Function ( "parameter 1", "parameter 2", "body method");
### page elements and related methods
- Gets the id of the page element method
var d = document.getElementById ( "d1" ); - Text content access and modify elements of
d.innerText
d.innerText = "abc"; - Value to retrieve and modify the text box
var I = document.getElementById ( "I1");
i.value obtaining
i.value = "xxx"; - To retrieve and modify elements html content
d.innerHTML
d.innerHTML = "<h1 of> ABC </ H. 1>";
Append + = d.innerHTML "<h1 of> ABC </ h1 of>";
(where the pay more spaces)
### String relevant
- Creating strings
- var s1 = "abc"; // single and double quotes are
- var s2 = new String(“abc”);
- Converted into string values
- parseFloat(“8”) 8
- parseInt(8.5) 8
- Number ( "8.5") 8.5 parseFloat action and the like
- String transfer case
- Turn capital str.toUpperCase ();
- Small letter str.toLowerCase ();
- Gets the string that appears
- Position str.indexOf ( 'b') from the first occurrence of a zero
- Position str.lastIndexOf ( 'b') the last to appear
- Interception string
- str.substring(start,?end);
- Replacement string
- str.replace (old, new); replacement of only a
- Split string
- var arr = str.split(".");
### mathematical correlation
- Random number Math.random (). 3 * 0-1
3-5 + 0-2. 3
25-36 +25 0-11
100-200 100 0-100 +
the parseInt (Math.random () * 101) +100
6- . 9
parsetInt (Math.random () *. 4) +6; - Rounding
num.toFixed (m); m represent reserved decimal places
18.23456.toFixed (4); 18.2346
#### Array related
- Creating an array
- var arr1 = [ "Hsiao Ming", 18, true];
- var arr2 = new Array();
- Add content to an array
- arr.push ( "Andy");
- arr.push(18);
- Like Java array traversal
var arr = [ "Bob", 18 is, to true];
for (var I = 0; I <arr.length; I ++) {
Alert (ARR [I]);
} - To retrieve and modify the array length
- the length of the array java immutable
arr.length // Get
arr.lenght = 3;
- Array reverse arr.reverse ();
- Array sort arr.sort (); Default collation sorting encoded in Unicode, then a ratio of the first complete than the second
-
Custom sorting:
var = ARR [18,11,26,22,2,7,3];
// custom ordering method
function mysort (A, B) {
return ba; // indicate ascending descending ba Representative
}
Alert ( arr.sort (mysort)); -
arr.sort(new Function(“a”,“b”,“return a-b;”));
### By Date
- Client server time and time
- Get Client Time
var d = new Date (); - Time to turn the string objects time 14:37:30 2019/5/8
var a Date new new D = ( "2019/5/8 14:37:30"); - Get and set the time stamp (from January 1, 1970 08:00:00)
d.getTime ();
d.setTime (); - Acquisition time component
d.getFullYear (); // Year
d.getMonth (); month from 0 +1
d.getDate (); day
d.getDay (); week
d.getHours (); // h
d. getMinutes (); min
d.getSeconds (); sec - Minutes acquiring date and get
d.toLocaleDateString ();
d.toLocaleTimeString ();
### Regular Expressions
- Scenario:
- Find Content
- Check text
- .: Matches any character except newline
- \ W: Matches any number, letter, underscore
- \ D: to match any number
- \ S: matches any blank
- ^: Beginning
- $: End
- For example:
- Beginning with m ^ m
- N $ n to the end
- Contains two digits \ d {2}
- Only two digits ^ \ d {2} $
- Numbers beginning with 3 ^ \ d {3}
- X beginning with the intermediate end 5 digits y ^ x \ d {5} y $
- M has a beginning end of the intermediate 3-5 digits n ^ m \ d {3,5} n $
- 6-10 alphanumeric underscores ^ \ W {6,10} $
- creating regular objects in two ways
- var reg = / rules / pattern; (two modes: i ignore case, g Global Search)
REG = / ^ \ {W} $ 6,10 /; - var reg = new RegExp (? "Rules", "mode");
REG = new new the RegExp ( "^ \ W {6,10} $");
- regular objects related to a method - Find what methods reg.exec (str)
var str = "you CAN NO CAN NO bb you up";
var = REG / NO /;- G If you do not find every time is the first
reg.exec (str); - If you add in the text g from the Find Next to find each one until the time could not find the return null
var = REG / NO / g;
reg.exec (str);
- G If you do not find every time is the first
- Calibrating method reg.test (STR);
var REG = / ^ you /;
reg.test (STR);
- canonical string and associated methods - Find what str.match (reg)
- If this method is to find a global search will find all of the one-time return to an array
- Alternative method str.replace (REG, new new);
REG = / NO / G;
str.replace (REG, "no");
#### modified class attribute value of the element
- div.className=“xxx”;
### How to make a page element hiding
- display: none elements hidden and out of the document flow, if the show comes back, need to change back to the default value of the element
- visibility: hidden (hidden) / visible (displayed) to hide elements without departing from the document flow
### custom objects
/* function Person(name,age){
//添加属性
this.name=name;
this.age=age;
//添加方法
this.run = function(){
alert("我叫:"+this.name+
"今年"+this.age);
}
}
//实例化对象
var p = new Person("张三",5);
p.run(); */
function Person(){}
var p = new Person();
//动态添加属性和方法
p.name = "张三";
p.age = 18;
p.run = function(){
alert("我叫:"+this.name+
"今年"+this.age);
}
//调用
//p.run();
//第二种实例化对象的方式
var p2 = {
"name":"李四",
"age":18,
"run":function(){
alert("我叫:"+this.name+
"今年"+this.age);
}
}
p2.run();
###DHTML
- Introduction: Dynamic (dynamic) HTML, not new technology, is to combine the pages together through the development of html, CSS, JavaScript called dynamic html
- DHTML include: BOM, DOM
- BOM: Browser Object Browser Object Model model, and includes browser-related content
- DOM: Document Object Model Document Object Model, and the page that contains relevant content
### BOM browser object model
#### window object
window object inside the property called global properties, methods, called global method, can be omitted when calling
# #### window inside a common method- parseInt() 和 parseFloat()
- alert () prompt box
- confirm () check box
- prompt () pop-up text box
- isNaN ()
##### window in common attributes
- location location
- location.href browser to access and modify the access address
to obtain location.href
modify location.href = "http://www.tmooc.cn"; - location.reload (); Refresh
- history history history of the current window
- history.length number of pages
- history.back () Back surface
- history.forward () Go to next page
- history.go (n) n positive negative Forward Back Refresh 0
- screen screen
- screen.width / height to get the screen resolution
- screen.availWidth / Height available screen resolution to give
- navigator navigation help
- navigator.userAgent; browser version information for
#### window-related events - Window click onclick event
- Page loaded onload event
- Page for focus events onfocus
- Page lost focus event onblur
#### eval () - It may be performed in the form of a string code js
#### by js code to add a style element
- . .Style element object style name = "value";
#### timer - Every piece of code execution period of the event
- Format: setInterval (methods, time intervals);
the setInterval (function () {
Alert ( "ha");
}, 1000);
### stops timer
var Timer = the setInterval (function () {}, 1000);
the clearInterval ( timer);
### DOM Document Object Model
#### find elements
- Acquired by the page element ID
var = document.getElementById D ( "D1"); - Get element by the tag name
var arr = document.getElementsByTagName ( "div" ); - Find by class attribute value element
var arr = document.getElementsByClassName ( "class" ); - Find by name attribute value element
var arr = document.getElementsByName ( "name" ); - Get body
document.body
#### created element object
- D = document.createElement var ( "div");
#### additive element
of the parent element .appendChild (target element);
#### insert elements
parent element .insertBefore (new element, brother element);
#### Delete elements of
the parent element .removeChild (deleted elements);
### event-related content
- Event: Event is some particular point in time, events include: mouse events, keyboard events, state change event
#### Event Categories
-
Mouse events: click events onclick, move the mouse events onmouseover, mouse out events onmouseout, mouse-down event onmousedown, mouse up event onmouseup, mouse motion events onmousemove
-
Keyboard events: keyboard press event onkeydown keyboard up event onkeyup
-
State change event: Get lost focus onblur onfocus focus window size changes onresize
value change event onchange event onsubmit form submission page loaded onload event
#### event object event
- Event object holds information related to the event
- Save the coordinates of the mouse event information event.clientX mouse / Y
- Keyboard events to save key information event.keyCode String.fromCharCode (65);
- Any event can get event source object
event source is to add a tag events
var obj = event.target || event.srcElement; (solve the compatibility written)
Binding ### events
- there are two different ways to bind- Add this property represents the window object event method through the inside of the tag event
- Dynamic binding: the event execution method for adding this js code representative of the event source to the element by
transmitting ### an event (event bubbling)
- If there are a plurality of elements within a range in response to events, the event delivery order is transferred from the bottom to the top (similar to bubble so called event bubbling)