JavaScript language history
● JavaScript is a script language developed by Netscape company (Netscape company of the United States), which is composed of
The utility model has the advantages of simple structure, convenient use, low requirements for users' own knowledge level and easy to learn and understand.
● Netscape named this scripting language LiveScript, which, like java, is also oriented to
It can be interpreted and run directly by the browser without compilation, rather than through Java
Over compiled.
● Netscape company sees that LiveScript has great development prospects, while SUN company (java) also thinks it can
Livescript was used to pave the way for the popularity of Java, so the two signed an agreement to change livescript to Java
For JavaScript, created this powerful WEB development tool.
JavaScript Language Overview
JavaScript is a literal script language, which is used to add various dynamic functions to web pages (JavaScript can operate web page content). It can be interpreted and run directly through the browser without compilation. Usually, JavaScript scripts realize their functions by embedding in HTML.
effect:
1. Respond to client mouse and keyboard events
2. Client page form data validation
3. Use JavaScript to dynamically change the style of page labels
What is the difference between javaScript and java
The same thing: they are all object-oriented languages
difference:
javaScript is a scripting language that runs in a web browser
java is a high-level language, which needs to be compiled and executed as a whole
Relationship between javaScript, HTML and CSS:
HTML is mainly used to build the main body of the web page, fill in the content of the web page, and realize the functions of hyperlinks, pictures, forms, tables and so on
Css is mainly used to better modify the properties of web page tags, add box model, floating, positioning and other functions
javaScript endows static Web pages with dynamic effects, enhances Web client interaction, and makes up for the defects of HTML
Specific functions:
1. Respond to events generated in the web page
2. Perform client form validation
3. Dynamically change label style
javaScript scripts are written in a group of script tags, which can be placed in the head or body. Generally, it is used to put them in the head. You can also write scripts in external. js files and import external. js files in html pages
1. Fill in internally
<html> <head> <script type="text/javascript"> alert("hello javaScript"); </script> </head> <body> </body> </html>
2. Write in external js file
<script src="js/test.js" type="text/javascript" charset="utf-8"></script> alert("From outside javascript file");
Basic grammar
variable
Declare variables with VaR keyword, such as var name;
var name = "LiHua" can be assigned at the same time;
Data types supported by JavaScript
1. Numerical type (number): including integer and floating-point numbers.
var a=4; alert(typeof(a)); /* Gets the data type of variable a */
2. Boolean: that is, logical value, true or false, which is often used to judge logical value
3. String type: composed of single or multiple text characters. Strings are described in single or double quotation marks (use single quotation marks to enter strings containing quotation marks.)
4. undefined type: undefined type is for declaring uninitialized variables
5. Object type
Arithmetic operator
+You can perform "addition" and "connection" operations. If one of the two operators is a string, javascript will convert the other into a string, and then connect the two operands.
Define function
Basic syntax of function definition:
function functionName([arguments]){ javascript statements [return expression] }
Function: indicates the keyword of function definition;
functionName: indicates the function name;
arguments: indicates the parameter list passed to the function. The parameters are separated by commas and can be empty;
statements: indicates the body of the function that implements the function;
return expression: indicates that the function will return the value of expression. It is also an optional statement.
Transformation of function data type
• parseInt(arg) converts the contents in parentheses to the value after integer. If there is a string in parentheses,
The numeric part at the beginning of the string is converted to an integer. If it starts with a letter, it returns
"NaN".
• parseFloat(arg) converts the string in parentheses to the value after the floating point number, and the value at the beginning of the string
The numeric part is converted to a floating-point number, and if it starts with a letter, "NaN" is returned.
• typeof (arg) returns the data type of the arg value.
• eval(arg) can operate on a string.
/* Use the eval function to run the string as a script */ var e="alert(11212)"; eval(e);
Built in object
String string
Length usage: returns the length of the string
method
charAt(n): returns a single character in the nth bit of the string
indexOf(char): returns the first occurrence of the specified char
lastIndexOf(char): similar to indexOf(), but starting from the back
substring(start,end): returns the substring of the original string. The string is a section of the original string from the start position to the previous position of the end position
substr(start,length): returns the substring of the original string, which is a length of the original string starting from the start position
Split (separator character): returns an array that is separated from the string object. The separator character > determines the separation place, and it itself will not be included in the returned array.
For ex amp le: '1 & 2 & 345 & 678'. split('&') returns the array: 1,2345678.
var str="vsdvsdvds"; console.log(str.length); console.log(str.substr(0,5));/* Start position, intercept length */ console.log(str.substring(0,5));/* Start position, intercept end position */
Array array
Array definition method:
var <Array name> = new Array();
This defines an empty array. To add array elements later, use: < array name > [subscript] = value;
If you want to initialize data directly when defining an array, use: VAR < array name > = new array (< element 1 >, < element 2 >, < element 3 >...);
Var < array name > = [< element 1 >, < element 2 >, < element 3 >...];
/* Method 1 of creating Array object*/ var array=new Array(); array[0]=1; array[1]=2; array[2]=3; array[3]="4"; console.log(array);
/* Method 2 of creating Array object*/ var array1=new Array(1,2,"aas",true); console.log(array1);
/*Method 3 for creating Array object*/
var array2=[1,2,"xasx",true];
console.log(array2); /* Used to connect multiple arrays */ console.log(array.concat(array1)); /* Returns and deletes the last element */ console.log(array.pop()); /* Adds an array element and returns a new length */ console.log(array.pop()); /* Adds a new array to the end and returns a new length */ console.log(array.push()); /* Used to delete the first element and return */ console.log(array.shift()); /* Returns the selected element from an existing array */ console.log(array1.slice(0,3)); /* Add / remove items to / from the array, and then return the deleted items */ console.log(array1.splice(1,2,0,0));/* (Start position of operation, number of operations, add element) */ /* Returns a string that strings the elements of an array */ console.log(array1.join("!")); console.log(array1.reverse());/* Reverse order output */
Date class
get date
new Date() returns the date and time of the current day
getFullYear() returns a four digit year
getDate() returns a day of the month (1 ~ 31)
getMonth() returns the month (0 ~ 11)
getDay() returns a day of the week (0 ~ 6)
getHours() returns the hour (0 ~ 23) of the Date object
getMinutes() returns the minutes (0 ~ 59) of the Date object
getSeconds() returns the number of seconds (0 ~ 59) of the Date object
Set date
setDate() sets a day of the month in the Date object (1 ~ 31))
setMonth() sets the month (0 ~ 11) in the Date object
setYear() sets the year (two or four digits) in the Date object
/* object type */ var date=new Date(); date.getFullYear(); date.getDate(); date.getHours(); console.log(date);
Math class
Math object that provides mathematical calculations of data.
PI returns π (3.1415926535...).
method
Math.abs(x) absolute value calculation;
Math.pow(x,y) power; y power of X
Math.sqrt(x) calculates the square root;
Math.ceil(x) rounds up a number
Math.floor(x) rounds down a number.
Math.round(x) rounds a number to the nearest integer
Math.random() returns a random number between 0 and 1
Math.max(x,y) returns the maximum of X and y
Math.min(x,y) returns the minimum of X and y
Event trigger
onclick() when the mouse clicks;
Ondbllick: double click the mouse;
The onblur() tag loses focus;
The onfocus() tag gets the focus;
onmouseover() the mouse is moved over a label;
onmouseout move the mouse away from a label;
onload() is to trigger the corresponding event handler after the web page is loaded;
onchange() means that the event handler is triggered when the current tag loses focus and the content of the tag changes.
Onkeydown keyboard press
Onkeyup keyboard lift
Event object
● the Event object represents the state of the Event, such as the key position of the keyboard keys and the position of the mouse.
Type event type
The mouse key where the Button is clicked
Alt key press ALT key to return true
CTRL key press Ctrl key to return true
shiftKey press shiftKey to return true
keyCode returns the code of the pressed key
offsetX the X axis of the mouse within the current label
offsetY the Y axis of the mouse within the current label
The clientX mouse is on the X axis inside the browser
The clientY mouse is on the Y axis inside the browser
screenX the X axis of the mouse in the display
Screen the Y axis of the mouse in the display
function test(a,e){ /* console.log(e.button); */ /* alert(a); */ console.log(e.offsetX+-----+e.offsetY); }
<input type="button" value="Button" onclick="test(1,event)"/>
function test(a,e){ //console.log(e.offsetX+"---"+e.offsetY); //console.log(e.screenX+"---"+e.screenY); console.log(e.keyCode); console.log(e.ctrlKey); console.log(e.altKey); console.log(e.shiftKey); } <input type="button" value="test" onmousedown="test(1,event)" />
Html DOM
DOM is the abbreviation of Document Object Model (tags in web pages). Through html dom, you can manipulate all tags of html documents with javaScript
Manipulate HTML tags through JavaScript
To operate, first get
There are four ways to do this:
1. Find the HTML tag by id
document.getElementById("id");
2. Find HTML tag by tag name
document.getElementsByTagName("p");
3. Find the HTML tag by the class name
document.getElementsByClassName("p");
4. Find the HTML tag by name
document.getElementsByName("name");
Html dom allows javaScript to change the content of html tags.
Change the properties of HTML tags
document.getElementById("username").value="new value"; document.getElementById("image").src="new.jpg";
The easiest way to modify HTML content is to use the innerHTML attribute
document.getElementById(*"div"*).innerHTML=*new HTML*
html dom allows javaScript to change the style of html tags.
Syntax:
document.getElementById("id").style.property=new style;
Example:
document.getElementById("p2").style.backgroundImage="url(bg.jpg)";
Browser built-in objects
All JavaScript global objects, functions, and variables automatically become members of window objects.
Global variables are properties of window objects.
Global functions are methods of window objects.
Even the document of html dom is one of the properties of the window object.
window.document.getElementById("header");
Common properties of Window objects:
window.innerHeight - The internal height of the browser window window.innerWidth - The internal width of the browser window window.parent Get parent window object(Call between parent and child)
Common methods for Window objects
window.open('url ',' name ',' features') - opens a new window
Features: an optional string that declares the features of the standard browser to be displayed in the new window.
width=100,height=100,top=100,left=100
<html> <head> <meta charset="utf-8"> <title></title> </head> <body> father<div id="divobj"></div> <iframe src="Introverted window exercise 2(son).html"></iframe> </body> </html>
<html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript"> function test(e){ var a=document.getElementById("child").innerHTML; /* var b=window.parent.document.getElementById("divobj"); Get the value from the parent tag and pass it to b through the method b.innerHTML=a; */ window.open("Introverted window exercise 1(father).html","name","width=300px,height=200px,left=200px,top=200px"); } </script> </head> <body> son<div id="child">1111</div> <input type="button" value="Submit" onclick="test(event)"> <a href="https://Www.baidu. COM /? TN = 56042972_18_hao_pg "target =" name "> Baidu < / a > <! -- where the target is opened -- > </body> </html>
Location object
The location object is used to get the address (URL) of the current page and redirect the browser to a new page.
The window.location object can be written without the prefix window.
Properties:
href sets or returns the full URL
method:
assign(url) loads a new document
reload() reloads the current document
replace(url) replaces the current document with a new document.
function assigndemo(){ location.assign("child.html"); //Load a new page and keep the original } function reloaddemo(){ location.reload();//Refresh current page } function replacedemo(){ location.replace("child.html"); //Load a new page to replace the current page }
time
By using JavaScript, we have the ability to execute after a set time interval
Instead of executing immediately after the function is called, we call it a timed event.
method:
setTimeout(""Function",""Time")Execute code sometime in the future clearTimeout()cancel setTimeout() setInterval(""Function",""Time")Repeat call every specified time clearInterval()cancel setInterval()
//After the specified time, the specified function is called and called only once. //After the specified time, the specified function is called. var t = setTimeout("test()",3000); //Calls the specified function every specified time var t1 = setInterval("test()",3000); function clearTime(){ //clearTimeout(t); / / cancel the specified timer clearInterval(t1); }