02_JavaScript - Basics of Web Development

JavaScript basics of web development

Learning objectives and content

1. Be able to describe the function of Javascript

2. Ability to use branch structure if statements to make logical judgments

3. Be able to use one of the loop statements

4. Able to define functions in javaScript

5. Ability to define objects in javaScript

6. Be able to describe the role of DOM

7. Able to operate HTML tag elements and their attributes through DOM

8. Ability to register HTML element events

1. Introduction to JavaScript

1. The power of JavaScript

Baidu Mind Map - Convenient thinking tool

2. What is JavaScript?

JavaScript is a programming language that runs on the client (browser) and is used to add dynamic functionality to web pages.

History of JavaScript:History of JavaScript

3. The role of JavaScript

① First purpose

To handle form validation operations

②Nowadays, a wide range of application scenarios

  1. Web special effects

  2. Server-side development (Node.js)

  3. Command line tools (Node.js)

  4. Desktop program (Electron)

  5. App(Cordova)

  6. game development

4. The difference between JavaScript, HTML and CSS

HTML: Provides the structure and content of a web page

CSS: Modify and beautify content

JavaScript: control page content and increase page dynamic effects

5. The composition of JavaScript

ECMAScript - the core of JavaScript

ECMAScript is the core of JavaScript and describes the basic syntax and data types of the language. ECMAScript is a set of standards that defines a language standard that has nothing to do with the specific implementation (it is the syntax specification of JavaScript)

BOM - Browser Object Model

A set of APIs for operating browser functions

BOM can be used to operate the browser window, such as: pop-up box, control browser jump, obtain resolution, etc.

DOM - Document Object Model

A set of APIs for manipulating page elements

DOM can regard HTML as a document tree, and the nodes in the tree can be operated through the API provided by DOM.

6. JavaScript writing position

JavaScript writing position is similar to CSS (inline style, embedded style, external style)

①Write within the lines

<input type="button" value="按钮" οnclick="alert('Hello World')" />

②Write in script tag

<head>
  <script>
    alert('Hello World!');
  </script>
</head>

③Write it in an external js file and introduce it into the page.

<script src="main.js"></script>

Tip:

① When introducing the script tag of an external js file, JavaScript code cannot be written before </body>

②css is introduced at the head and js files are introduced at the bottom

2. JavaScript basic syntax

1. Variables

1.1. Definition of variables

Use the var keyword to define variables in js

①Syntax of variables

var userName = 'linux';
var age = 18;

②Declare multiple variables at the same time

var age, name, sex;
age = 18;
name = 'centos';

③Declare multiple variables at the same time and assign values

var age = 23, name = 'shell';

1.2. Naming rules and specifications for variables

Rules - must be followed, if not followed an error will be reported

  • It consists of letters, numbers, underscores, and the $ symbol, and cannot start with a number.

  • Cannot be keywords and reserved words, such as: for, while.

  • case sensitive

Specifications - It is recommended to follow them. If you don’t follow them, you will not get an error.

  • Variable names must be meaningful

  • Observe camelCase nomenclature. The first letter should be lowercase, and the first letter of subsequent words should be capitalized. For example: userName, userPassword

2. Data type

Commonly used data types are: Number, String, Boolean

2.1. Number type

Numeric literal: a representation of a fixed value of a numerical value

100 183.5

2.2. String type

A string is a piece of content enclosed in quotation marks. ‘linux’’centos’ ‘sa’ ‘devops’ is a string in javaScript. Both single and double quotation marks can be used. It is recommended to use single quotation marks to escape characters.

String length The length attribute can be used to get the length of the string

var str = "I am an operation and maintenance personnel"
console.log(str.length);

String splicing Multiple strings can be spliced ​​using the + symbol

console.log(‘linux’+’centos’);

2.3. Boolean type

Literals: true and false

Tip:

typeof (variable) checks the type of data

Number (string type) Convert string to number type

3. Comments

Comment function:

1. Explanation

2. The commented code will not be executed.

①Single line comment

//This is a variable
var name = ‘linux’;

②Multi-line comments

/*
var name = ‘linux’;
var age = 18;
var job = 'server';
*/

4. Operator

Operator, very similar to operators in mathematics

4.1. Arithmetic operators

+ add

- reduce

* take

/ remove

% Remainder: Perform division operations until the divisor cannot be divided anymore, and the remaining number is the remainder.

4.2. Increment and decrement operators

Unary operator: An operator with only one operand. The increment and decrement operators are unary operators.

++ Self +1

-- Self-1

Case demonstration: The difference between pre-++ and post-++

4.3. Logical operators

&& and If both operands are true at the same time, the result is true, otherwise both are false. One loss and both are lost. Multiple conditions are met at the same time.

|| or if one of the two operands is true, the result is true, otherwise it is false. Just satisfy one of the conditions.

! Non negation does not meet this condition

4.4. Comparison operators

< > >= <= == != =\== !\==

The difference between \== and ===:

==Only make worthy comparisons

===If the type and value are equal at the same time, they are equal

4.5. Assignment operator

=

+= -= *= /= %=

Self-operation first, then assignment

var num = 6;
num += 6; //Equivalent to num = num+6. Guess what it equals?
num /=2; //Equivalent to num = num/2. Guess what it equals?

5. Branch structure

Branch statements are generally used to judge different situations and perform corresponding processing in code blocks.

5.1. if statement

①Single branch statement (if) Syntax:

if (/* conditional expression */) {
  //Execute statement
}

②Double branch statement (if...else)

grammar:

if (/* conditional expression */){
  // Establish execution statement
} else {
  // Otherwise execute the statement
}

③Multi-branch statements (if...elseif...else)

grammar:

if (/* condition 1 */){
  // Establish execution statement
} else if (/* condition 2 */){
  // Establish execution statement
} else if (/* condition 3 */){
  // Establish execution statement
} else {
  //Finally execute the statement by default
}

Case: Find the maximum value of two numbers

Determine whether it is an odd or even number

5.2. switch statement

grammar:

switch(n)
{
case 1:
  //Execute code block 1
  break
case 2:
  //Execute code block 2
  break;
default:
  //n code that is not executed simultaneously with case 1 and case 2
}

Case: What day is it today?

day=new Date().getDay()

6. Loop structure

In JavaScript, there are three types of loop statements, for, while, do..while loops

while and do...while are generally used to solve situations where the number of loops cannot be determined. It is generally common to use a fixed number of times, and it is more common to use for.

6.1. for statement

grammar:

for (initialization expression 1; judgment expression 2; increment expression 3) {
  // Loop body 4
}

6.2. while statement

//When the loop condition is true, execute the loop body,
// When the loop condition is false, end the loop.
while (loop condition) {
  //Loop body
}

6.3. do...while statement

grammar:

do {
  // Loop body;
} while (loop condition);

Tip:

do...while is very similar to while in use. The difference is that do...while will perform an operation regardless of whether the condition is true or not. That is to say, act first and judge later.

6.4, continue and break keywords

break: Immediately jump out of the entire loop, that is, the loop ends, and start executing the content after the loop (jump directly to the braces)

continue: Immediately jump out of the current loop and continue to the next loop (jump to i++)

7. Array

An array is an ordered list that can store any data in the array, and the length of the array can be dynamically adjusted.

7.1. Definition of array

grammar:

//Create an empty array
var scar = [];
//Create an array of numbers
var arr1 = [1,2,3,4,5];
//Create an array containing strings
var arr2 = ['linux','centos','redhat'];

Tip:

// You can get the length of the array through the length property of the array

console.log(arr3.length);

// You can set the length attribute to change the number of elements in the array

arr2.length = 0;

7.2. Obtain access data elements

grammar:

// Format: array name [subscript] subscript is also called index
//The subscript starts from
// Function: Get the value corresponding to the subscript of the array. If the subscript does not exist, undefined is returned.
var arr2 = ['linux','centos','redhat'];
arr2[0];   //linux
arr2[2];   //redhat
arr2[3]; //undefined ?Why?

7.3. Traverse the array

Traverse the array: perform the method once for each element of the array.

grammar:

for(var i = 0; i < arr.length; i++) {
	// Fixed structure for array traversal
}

7.4. Operations on array elements

grammar:

//Format: array name [subscript/index] = value;
//If the value corresponding to the subscript exists, replace it. If it does not exist, it will be added.
var arr2 = ['linux','centos','redhat'];
//replace redhat with devops
arr2[2] = ‘devops’;
//Add new elements to the array
arr2[3] = 'to';

How to operate related arrays:

8. Function

Encapsulate a piece of code to facilitate reuse. The code is also clearer and the structure is clearer.

8.1. Definition of functions

grammar:

function function name() {
  // function body
}

Function expression:

var fn = function () {
  // function body
}

Tip:

After the function is defined, it will not be executed. It needs to be called before it can be executed.

8.2. Function parameters

Parameters: The inside of the function body is a closed space, and external values ​​need to be passed to the inside of the function body through parameters.

grammar:

//Function declaration with parameters
function function name (formal parameter 1, formal parameter 2, formal parameter 3...) {
  //Function body
}
//Function call with parameters
Function name (actual parameter 1, actual parameter 2, actual parameter 3)

8.3. Return value of function

After the function is called and executed, not all scenarios need to print out the results. In some business scenarios, it is necessary to return the execution result of the function to facilitate subsequent operations. At this time, you can let the function return, which is the return value of the function. Functions can return the return value of the function through the return keyword syntax.

Tip:

①The code after return will no longer be executed

②The default return value of the function is undefined

grammar:

//Declare a function with a return value
function function name (formal parameter 1, formal parameter 2, formal parameter 3...) {
  //Function body
  return return value;
}
//You can receive this return value through a variable
var variable = function name(actual parameter 1, actual parameter 2, actual parameter 3...);

9. Object

js is an object-based language

Object: consists of properties and methods

The definition format of objects in js is similar to the learned dictionary. It can be seen as a collection of functions

grammar:

var person = {
  name: 'linux',
  age: 18,
  sex: true,
  say: function () {
    console.log(this.name);
  }
};

3. DOM

After learning DOM, you can use javaScript to control the page (style, element attributes, hidden display, etc.)

1. What is DOM

DOM is the Document Object Model, which is a tree structure generated by the browser so that programming languages ​​can easily access the HTML structure.

The entire page can be obtained through document in the DOM.

2. Get page elements

①getElementById() Root id 获取Element

②getElementsByTagName() Get elements (collection) according to tag name

==③querySelector()== Use the selector to get elements and only return the first matching element

==④querySelectorAll()== Use the selector to get elements and return all matching elements (set)

3. Set element attributes

- After obtaining the element, you can set the corresponding attributes of the element and change the effect of the page.

- Attributes of ordinary elements

- The attributes of tags in HTML generally correspond to the attributes of elements in DOM, and the attributes of elements in DOM, for example:

title、src、id 等

- The content between tags can be set through the ==innerHTML== attribute of the element

- Dynamically generate lists through innerHTML

- Attributes of form elements

- value、checked、selected、disabled

- Traverse text boxes and assign values ​​to all text boxes

- Get the options in the drop-down box and set the items displayed in the drop-down box

- Disable button

Case:

1. Use js to dynamically generate a list

2. Operate the form and obtain form-related values.

4. Register event

The event mechanism in DOM can implement some common operations. For example: response to clicking a button, pressing the keyboard, etc.

grammar:

element.onclick = function () {
  alert('hello world');
};

Common events:

Case: Implement the click event of the button and cancel the transfer of the a label.

//Button click event
document.querySelector('button').onclick = function(){
           alert('Binded and executed click event');
}
//Cancel the default jump of the a tag
document.querySelector('a').onclick = function(){
           return false;
}

5. Change the style of elements

①Change inline style

element.style.color = 'red';

②Change class style

element.className = 'active';

Guess you like

Origin blog.csdn.net/qq_57747969/article/details/135035746