Front-end js basics


JavaScript basics

1. Pre-knowledge

Written form of JS

1. Inline

Embed directly inside the html element

<input type="button" onclick="alert('hello')">

2. Embedded

write in the script tag

<script>
  alert('hello');
</script>

3. External formula

write to a separate .jsfile

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

**Note, in this case, the code cannot be written in the middle of the script tag. It must be empty (the code will not be executed) **

note

//单行注释
/*
多行
注释
*/

input Output

input: prompt

pop up an input box

<script>
        let name = prompt("请输入您的姓名:");
        
</script>

Output in browser console

console.log("hello");

console is an "object" in js
. It means to take a certain property or method in the object. It can be understood intuitively as "the"
console.log can be understood as: use the "log" method of the "console" object

2. Basic Grammar

JS data type

basic data type

Several types built into JS

  • umber: number. Integers and decimals are not distinguished.
  • boolean: true true, false false.
  • string: string type.
  • undefined: Only the unique value undefined. Indicates an undefined value.
  • null: Only the unique value null. Indicates an empty value

**Integers and floating-point numbers are not distinguished in JS, and they are all represented by "number type"**

JS is a dynamically typed language, that is, the type of a variable can change during runtime

let a = 10;
a = "test"
a = true

special value

  • Infinity: Infinity, greater than any number. It means that the number has exceeded the range that JS can express.
  • -Infinity: Negative infinity, less than any number. It means that the number has exceeded the range that JS can express.
  • NaN: Indicates that the current result is not a number

string

JS strings can also be concatenated, by lengthcalculating the length of the string

<script>
    let str1 = "hello"
    let str2 = "world";
    console.log(str1+10);
    console.log(str1+str2);
    console.log(str1.length); 
</script>
//输出
hello10
helloworld
5

boolean Boolean type

Boolean was originally a concept in mathematics (Boolean algebra).
Boolean is of great significance in computers, and it is often necessary to match conditions/loops to complete logical judgments.
Boolean is treated as 1 and 0 when it participates in operations

console.log(true + 1);
console.log(false + 1);

undefined undefined data type

If a variable has not been initialized, the result is undefined, which is of type undefined

var a;
console.log(a);

Undefined is added to a number, and the result is NaN

null empty value type

var b = null;
console.log(b + 10); // 10
console.log(b + "10"); // null10

Note:
Both null and undefined mean that the value is illegal, but the emphasis is different.
Null means that the current value is empty. (equivalent to having an empty box)
undefined means that the current variable is undefined. (equivalent to not even having a box

array

Loop branch logic operations are all the same as Java types, directly look at the array

create array

Created using the new keyword

// Array 的 A 要大写
let arr = new Array();

Created using literals

let arr = [];
let arr2 = [1, 2, 'haha', false]; // 数组中保存的内容称为 "元素"

get array element

Access array elements using subscripts (starting from 0)

let arr = ['张三', '李四', '王五'];
console.log(arr);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
arr[2] = '赵六';
console.log(arr);

Add new array element

1. Add elements by modifying length

let arr = [9, 5, 2, 7];
arr.length = 6;
console.log(arr);
console.log(arr[4], arr[5]);

2. Add by subscript

If the subscript exceeds the range of the assigned element, a new element will be inserted at the specified position

let arr = [];
arr[2] = 10;
console.log(arr)

At this time, [0] and [1] of this array are undefined

3. Use push to add elements

let arr = [1,2,3];
arr.push('hhy');
console.log(arr);

delete an element in an array

Remove elements using the splice method

let arr = [9, 5, 2, 7];
// 第一个参数表示从下表为 2 的位置开始删除. 第二个参数表示要删除的元素个数是 1 个
arr.splice(2, 1);
console.log(arr);
// 结果
[9, 5, 7]

function

grammatical format

// 创建函数/函数声明/函数定义
function 函数名(形参列表) {
    
    
    函数体
    return 返回值;
}
// 函数调用
函数名(实参列表) // 不考虑返回值
返回值 = 函数名(实参列表) // 考虑返回值

The function definition does not execute the content of the function body, it must be called before it will be executed. It will be executed several times after calling it several times

function hello() {
    
    
	console.log("hello");
}
// 如果不调用函数, 则没有执行打印语句
hello();

When the function is called, it enters the internal execution of the function, and when the function ends, it returns to the calling position and continues to execute. It can be observed with the help of a debugger. There is
no requirement for the sequence of function definition and calling. (This is different from variables, variables must be defined before use )

// 调用函数
hello();
// 定义函数
function hello() {
    
    
	console.log("hello");
}

function expression

Another way to define a function

let add = function() {
    
    
    let sum = 0;
    for (var i = 0; i < arguments.length; i++) {
    
    
        sum += arguments[i];
    }
    return sum;
}
console.log(add(10, 20)); // 30
console.log(add(1, 2, 3, 4)); // 10
console.log(typeof add);

At this time, a writing method like function() { } defines an anonymous function, and then expresses the anonymous function as a variable.
Later, the function can be called through the add variable.
Functions in JS can be stored in variables, or Can be used as parameters or return values ​​of other functions

object

JavaScript objects are basically the same as Java objects in concept. Only the specific syntax table entries are quite different

Create objects using literals

var a = {
    
    }; // 创建了一个空的对象
var student = {
    
    
    name: '张三',
    height: 188,

    sayHello: function() {
    
    
    	console.log("hello");
    }
};
  • Use { } to create an object
  • Properties and methods are organized as key-value pairs.
  • Used between key-value pairs, split. After the last attribute, optional
  • Between keys and values ​​use: split.
  • The value of the method is an anonymous function

user target audience

// 1. 使用 . 成员访问运算符来访问属性 `.` 可以理解成 "的"
console.log(student.name);
// 2. 使用 [ ] 访问属性, 此时属性需要加上引号
console.log(student['height']);
// 3. 调用方法, 别忘记加上 ()
student.sayHello();

Create objects using new Object

let student = new Object(); // 和创建数组类似
student.name = "张三";
student.height = 180;
student['weight'] = 170;
student.sayHello = function () {
    
    
console.log("hello");
}
console.log(student.name);
console.log(student['weight']);
student.sayHello();

Note that objects created with { } can also use student.name = "Li Si"; to add attributes at any time

Create objects using constructors

<script>
        let person1 = {
    
    
            name: "张三",
            sex: "男",
            eat: function() {
    
    
                console.log("吃饭");
            }
        }
        let person2 = {
    
    
            name: "李四",
            sex: "女",
            eat: function() {
    
    
                console.log("吃饭");
            }
        }
    </script>

At this time, it is more troublesome to write. Using the constructor can extract the creation of the same attributes and methods, simplifying the development process

function 构造函数名(形参) {
    
    
this.属性 =;
this.方法 = function...
}
var obj = new 构造函数名(实参);

Notice:

  • Use the this keyword inside the constructor to indicate the object currently being constructed.
  • The first letter of the function name of the constructor is usually capitalized.
  • The function name of the constructor can be a noun.
  • Constructors don't need to return
  • The new keyword must be used when creating an object
<script>
        function Person(name, sex) {
    
    
            this.name = name;
            this.sex = sex;
            this.eat = function() {
    
    
                console.log(name+"吃饭");
            }
        }
        let person1 = new Person('张三','男');
        let person2 = new Person('李四','女');
        person1.eat();
    </script>

The execution process of new:

  1. First create an empty object { } in memory
  2. this points to the empty object just now (use the object in the previous step as the context of this)
  3. Execute the code of the constructor to create properties and methods for the object
  4. Return this object (the constructor itself does not need to return, it is done by new)

3. WebAPI

JS is divided into three major parts

  • ECMAScript: Basic Syntax
  • DOM API: Manipulate page structure
  • BOM API: Operate the browser

WebAPI includes DOM + BOM

DOM tree

The structure of a page is a tree structure called DOM tree

insert image description here

  • Document: A page is a document, represented by document.
  • Element: All tags in the page are called elements. Use element to represent.
  • Node: All content in a web page can be called a node (label node, comment node, text node, attribute node, etc.). Use node to represent.

get element

Elements can be obtained through syntax similar to CSS selectors plus corresponding methods

**querySelector&querySelectorAll **

Using querySelector can fully reuse the knowledge of CSS selectors learned earlier to achieve a faster and more accurate way to obtain element objects

  • querySelector will return the first of the selected elements (the first element that appears)
  • querySelectorAll, it will return all the selected elements in the form of an array
<body>
    <div class="one">1</div>
    <div id="two">2</div>
    <div></div>
    <script>
        let cls = document.querySelector(".one");
        let id = document.querySelector('#two');
    </script>
</body>

or select multiple

<body>
    <div class="one">1</div>
    <div id="two">2</div>
    <div3></div>
    <script>
        let all = document.querySelectorAll('div');
    </script>
</body>

event

Basic concept
JS To build a dynamic page, it needs to perceive the user's behavior.
Some operations of the user on the page (click, selection, modification, etc.) will generate events in the browser, which are acquired by JS, so as to make more complex Interactive operation.
The browser is a sentinel, detecting the enemy’s situation (user behavior). Once the user reacts (triggers specific actions), the sentinel will light the beacon (event) of the beacon tower, and the rear can decide the next step based on the beacon enemy strategy.

The three elements of the event

  1. Event source: which element triggered
  2. Event type: is it clicked, selected, or modified?
  3. Event handler: how to proceed further. Often a callback function

example

<body>
    <input type="button" class="but" value="点击">
    <script>
        let but = document.querySelector('.but');
        but.onclick = function() {
    
    
            alert("触发点击事件");
        }
    </script>
</body>
  • The but button is the event source.

  • Click is event type

  • function This anonymous function is the event handler

  • Where but.onclick = function() This operation is called registration event/binding event

    Note: This anonymous function is equivalent to a callback function. This function does not need to be called by the programmer, but is handed over to the browser, and the browser will automatically call it at the right time (when the click operation is triggered)

operating elements

**Get/modify element content**

1.innerText

Element.innerTextProperty representing the "rendered" text content of a node and its descendants

<div>
    <span>hello world</span>
    <span>hello world</span>
</div>
<script>
    let div = document.querySelector('div');
    // 读取 div 内部内容
    console.log(div.innerText);
    // 修改 div 内部内容, 界面上就会同步修改
    div.innerText = 'hello js <span>hello js</span>';
</script>

It can be seen that the html structure inside the div cannot be obtained through innerText, only the text content can be obtained.
When modifying the page, the span tag will also be set as text

2.innerHTML

Element.innerHTMLAttribute to set or get descendants of elements represented by HTML syntax

<div>
    <span>hello world</span>
    <span>hello world</span>
</div>
<script>
    var div = document.querySelector('div');
    // 读取页面内容
    console.log(div.innerHTML);
    // 修改页面内容
    div.innerHTML = '<span>hello js</span>'
</script

innerHTML uses more scenarios than innerText

Get/modify element attributes

It can be directly modified through the properties of the Element object, which can affect the page display effect

<img src="test.jpg" alt="图片" title="这是一张图片">
<script>
    var img = document.querySelector('img');
    // console.dir(img);
    console.log(img.src);
    console.log(img.title);
    console.log(img.alt);
</script>

You can also modify properties directly

<img src="test.jpg" alt="图片" title="这是一张图片">
<script>
let img = document.querySelector('img');
img.onclick = function () {
      
      
    if (img.src.lastIndexOf('test') !== -1) {
      
      
        img.src = './demo.jpg';
    } else {
      
      
        img.src = './cat.jpg';
    }
}
</script>

At this point, click on the picture to switch the display status of the picture. (Two pictures need to be prepared in advance)

Get/modify form element attributes

The following attributes of the form (mainly the input tag) can be modified through DOM

  • value: the value of input.
  • disabled: disabled
  • checked: checkbox will use
  • selected: the drop-down box will use
  • type: type of input (text, password, button, file, etc.)
<input type="button" value="播放">
<script>
let btn = document.querySelector('input');
    btn.onclick = function () {
      
      
    if (btn.value === '播放') {
      
      
    	btn.value = '暂停';
    } else {
      
      
    	btn.value = '播放';
    }
}
</script>
<body>
    <div>
        <input type="checkbox" class="check">吃饭<br/>
        <input type="checkbox" class="check">睡觉<br/>
        <input type="checkbox" class="check">打游戏<br/>
        <input type="checkbox" class="all">全选<br\>
    </div>
    <script>
        let all = document.querySelector('.all');
        let inputs = document.querySelectorAll('.check');
        all.onclick = function() {
      
      
            for (let i = 0; i < inputs.length; i++) {
      
      
                inputs[i].checked = all.checked;
            }
        }
        console.log(all.checked);
        for (let i = 0;  i < inputs.length; i++) {
      
      
            inputs[i].onclick = function() {
      
      
                for (let i = 0; i < inputs.length; i++) {
      
      
                    if (inputs[i].checked == false) {
      
      
                        all.checked = false;
                        return;
                    }
                }
                all.checked = true;
            }
        }
        
    </script>
</body>

Get/modify style properties

element.style.[属性名] = [属性值];
element.style.cssText = [属性名+属性值];

Click to enlarge font

<div style="font-size: 20px; font-weight: 700;">
点我放大
</div>
<script>
    var div = document.querySelector('div');
    div.onclick = function () {
    
    
    var curFontSize = parseInt(this.style.fontSize);
    curFontSize += 10;
    this.style.fontSize = curFontSize + "px";
}
</script>

Class Name Style Manipulation

element.className = [CSS 类名];

Tap the background to toggle day/night mode

   <style>
        * {
      
      
    
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html,body {
      
      
            width: 100%;
            height: 100%;
        }
        .daytime {
      
      
            background-color: rgb(51, 51, 51);
            width: 100%;
            height: 100%;
            color: black;

        }
        .evening {
      
      
            background-color: rab(243,243,243);
            width: 100%;
            height: 100%;
            color: black;
        }
    </style> 

<body>
    
    <div class="daytime">
        <p>这是一段话</p>
        <p>这是一段话</p>
        <p>这是一段话</p>

    </div>
    <script>
        let div = document.querySelector('.daytime,.evening');
        div.onclick = function() {
      
      
            if (div.className == 'daytime') {
      
      
                div.className = 'evening';
            } else {
      
      
                div.className = 'daytime'
            }
        }
    </script>
</body>

operation node

in two steps

  1. Create element nodes
  2. Insert the element node into the dom tree

Create element nodes

Use the createElement method to create an element.

let element = document.createElement(tagName)

example

<div class="container">
</div>
<script>
    var div = document.createElement('div');
    div.id = 'mydiv';
    div.className = 'box';
    div.innerHTML = 'hehe';
    console.log(div);
</script>

At this time, it is found that although a new div is created, the div is not displayed on the page. This is because the newly created node has not been added to the DOM tree

Insert a node into the dom tree

Use appendChild to insert a node after the last child of the specified node

<div class="container">
</div>
<script>
    var div = document.createElement('div');
    div.id = 'mydiv';
    div.className = 'box';
    div.innerHTML = 'hehe';
    var container = document.querySelector('.container');
    container.appendChild(div);
</script>

Use insertBefore to insert the node before the specified node

let insertedNode = parentNode.insertBefore(newNode, referenceNode);
<div class="container">
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
</div>
<script>
    let newDiv = document.createElement('div');
    newDiv.innerHTML = '我是新的节点';
    let container = document.querySelector('.container');
    console.log(container.children);
    container.insertBefore(newDiv, container.children[0]);
</script>
  • Use this in the event callback function to get the element currently processing the event.
  • The parent element of the current element can be obtained through the this.parentNode property

delete node

Use removeChild to delete child nodes

oldChild = element.removeChild(child);
  • child is the node to be deleted
  • element is the parent node of child
  • The return value is the deleted node
  • The deleted node is only deleted from the dom tree, but it is still in memory and can be added to other positions in the dom tree at any time.
    pendChild(div);

使用 insertBefore 将节点插入到指定节点之前 

```javascript
let insertedNode = parentNode.insertBefore(newNode, referenceNode);
<div class="container">
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
</div>
<script>
    let newDiv = document.createElement('div');
    newDiv.innerHTML = '我是新的节点';
    let container = document.querySelector('.container');
    console.log(container.children);
    container.insertBefore(newDiv, container.children[0]);
</script>
  • Use this in the event callback function to get the element currently processing the event.
  • The parent element of the current element can be obtained through the this.parentNode property

delete node

Use removeChild to delete child nodes

oldChild = element.removeChild(child);
  • child is the node to be deleted
  • element is the parent node of child
  • The return value is the deleted node
  • The deleted node is just deleted from the dom tree, but it is still in memory and can be added to other positions in the dom tree at any time.
  • If the child node in the above example is not a child node of the element node, the method will throw an exception

Guess you like

Origin blog.csdn.net/weixin_53946852/article/details/129485685