JavaScript | DOM API Manipulating Elements

1. WebAPI background knowledge

JS is divided into three major parts:

  • ECMAScript: Basic syntax part
  • DOM API: Manipulating page structure
  • BOM API: operating browser

If you want to write actual programs, it is not enough to know the language. You also need to master the relevant "ecology". The supporting libraries/frameworks.
For running JS on the browser, the most core library is the DOM API.

It is the native interface provided by the browser for JS.
Based on this interface, you can operate on the elements on the page.

DOM => Document Object Model

In HTML, each html tag is regarded as an object that can be manipulated in JS. Operating this object can affect the display of the interface.

The API provided by the browser for JS is very rich, and there are many groups of
DOM API
BOM APl .
In fact, there are also some other
websocket APl, canvas APl...
collectively called WebAPI, we mainly introduce DOM

The native DOM API can be used, but it is not convenient.
Therefore, in addition to the native API, there are also a large number of third-party libraries/frameworks. Among them, jquery is the most well-known library,
Vue, React and other front-end frameworks, which are essentially based on DOM. package

jQuery

jQuery is a cross-browser JavaScript library that simplifies operations between HTML and JavaScript.
It is characterized by lightweight, rich DOM selectors, event, style, animation support, Ajax operation support, and strong scalability.

Bootstrap

boostrap is a framework that pursues consistency.
It is characterized by cross-device, cross-browse, responsive layout, supports HTML5 CSS3, and supports less dynamic style expansion.

jQuery UI

jquery ui is an extension of jquery to the desktop and can be configured through a visual interface.

API:

  • API is a broader concept, while WebAPI is a more specific concept, specifically DOM+BOM

  • The so-called API is essentially some ready-made functions/objects that can be used by programmers to facilitate development. It is
    equivalent to a toolbox, but the toolboxes used by programmers are numerous and have complex functions.

DOM:

  • DOM stands for Document Object Model.

  • The W3C standard provides us with a series of functions that allow us to operate:

    • Web content
    • Web page structure
    • Web page style

DOM tree:

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

Important concepts:

  • Document: A page is a document, represented by document.

  • Element: All tags on the page are called elements, represented by element.

  • Node: All content in a web page can be called a node (label node, comment node, text node, attribute node, etc.) and is represented by node

These documents and other concepts correspond to objects in JS code,
so it is called "Document Object Model"


2. Get elements

1、querySelector

  • If you want to operate elements on the page, you need to get the corresponding JS object first.
  • DOM provides a set of APIs that can obtain elements of web pages, the most important two are:
    querySelector,querySelectorAll


In fact, it is a global object in the property page of an object such as document . Once a page is loaded, a global variable will be automatically generated, called document. There are some properties and methods in it, allowing us to manipulate the content of the page.

<div class="one">
    one
</div>

<div class="two">
    two
</div>

<ul>
    <li>
       three 
    </li>
</ul>

<script>
    // querySelector 参数就是一个 CSS 的选择器
    let div = document.querySelector('.one');
    console.log(div);

    // id 选择器
    let obj = document.querySelector('#two');
    console.log(obj);

    // 复合选择器
    let obj2 = document.querySelector('ul li');
    console.log(obj2); 
</script>

Page results:

one

two

  • three

2、querySelectAll

<ul>
    <li>aaa</li>
    <li>bbb</li>
    <li>ccc</li>
</ul>

<script>
    let obj2 = document.querySelector('ul li');
    console.log(obj2); 
</script>

Insert image description here

When the selector of querySelector parameter matches multiple elements , the object returned at this time is the first element in the matching result
. In this case, if we want to select all these li , we need to use querySelectAllquerySelectAll What is returned is an "array", which contains all selected elements.

let obj2 = document.querySelectorAll('ul li');

Insert image description here

But to be precise, querySelectorAllwhat is returned is not a real native array, but an object . However, this object has length and can also access internal elements through subscripts.
Such an object is very similar to an array (exactly the same). called a "pseudo array"


3. Events

1. What is an event?

  • To build dynamic pages with JS, you need to sense user behavior
  • Some of the user's operations on the page (click, select, modify, etc.) will generate events in the browser, which are obtained by JS, allowing for more complex interactive operations.
  • 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 smoke (event), and the rear can use the smoke to decide the next enemy strategy.

Many codes in JS are triggered through "events"

Events are the browser's "general name" for user operations (to be precise, events may not all be generated by user operations, but most of them are)

For example, if the mouse moves on the page, a mouse move event will be generated.
For another example, if the mouse clicks somewhere on the page, a mouse click event will be generated. For another example, using the mouse wheel to scroll the page will generate a set of scroll events. For another example, when the user presses a key on the keyboard, a keyboard event will also be generated. For another example, if the user modifies the browser window size, a window size change event will also be generated.

One of the main tasks of JS is to perform different processing on different events.


2. Three elements of the event

  • Event source : Which HTML element generated the event.
  • Event type : mouse movement/mouse click/keyboard event/window size change event…
  • Event handler : When an event occurs, what kind of JS code is executed and how to handle it further is often a callback function.

3. Click event

<!-- 事件源:button -->
<button>这是一个按钮</button>

<script>
    let button = document.querySelector('button');
    // 事件类型:onclick   事件处理函数:function
    button.onclick = function() {
    
    
        alert('hello');
    }
</script>

Call this function a callback function : This function will not be called immediately, but will be automatically called by the library/framework when appropriate.

Another way of writing: This way of writing makes the page (HTML) more messy. We hope that the structure, style, and behavior can be separated.

<button onclick="f()">这是一个按钮</button>

<script>
    function f() {
    
    
        alert('hello');
    }
</script>

4. Operation elements

Operation = Get + Modify

  1. Manipulate element content
  2. Manipulate element attributes
  3. Manipulate the style of the element

1. Manipulate element content

This is achieved through an attribute innerHTML in the object (what does the html code contained in the element look like)

1.1. Print content

<div id="screen">hello world</div>

<button id="btn">这是一个按钮</button>

<script>
    let btn = document.querySelector('#btn');
    btn.onclick = function() {
    
    
        let screen = document.querySelector('#screen');
        console.log(screen.innerHTML);
    }
</script>

Insert image description here

When we click the button multiple times, we can see that multiple pieces of data are not displayed on the console, but a number is displayed. The console will merge the same prints into one by default. This can be set in the console. Group similar messages

Insert image description here


1.2. Get content button

<div id="screen">
    <ul>
        <li>aaa</li>
        <li>aaa</li>
        <li>aaa</li>
    </ul>
</div>

<button id="btn">获取内容按钮</button>

Insert image description here


1.3. Modify content button

<div id="screen">
    <ul>
        <li>aaa</li>
        <li>aaa</li>
        <li>aaa</li>
    </ul>
</div>

<button id="btn">修改内容按钮</button>

<script>
    let btn = document.querySelector('#btn');
    btn.onclick = function() {
    
    
        let screen = document.querySelector('#screen');
        screen.innerHTML = '<h1>修改后的内容</h1>'
    }
</script>

Insert image description here


1.4. Click to add one

The div displays an integer and a button. Every time the button is clicked, the integer inside is +1.

Note: Here, innerHTML gets the string type. If you want to add numbers, you need to convert the string into an integer.

let val = screen.innerHTML;
console.log(typeof(val)); // string

val = parseInt(val);

parselnt in Java is a member method of Integer class. Here parselnt in JS is equivalent to a global function

Since JS is a dynamic type, after converting it to a number, it can still be assigned to valval, so from the string => number type

<div id="screen">
    0
</div>

<button id="plus">+</button>

<script>
    let plusBtn = document.querySelector('#plus');
    plusBtn.onclick = function() {
    
    
        // 1、获取 screen 的值
        let screen = document.querySelector('#screen');
        let val = screen.innerHTML;
        val = parseInt(val);

        // 2、将这个值 + 1
        val = val + 1;
        
        // 3、把新值写回去
        screen.innerHTML = val;
    }
</script>

Insert image description here


1.5. Click input to add one

<input type="text" id="screen">

As a single tag (single dog), input is not worthy of having innerHTML. Here, the internal content is obtained through the value attribute of input.

<input type="text" id="screen" value="0">
<button id="plus">+</button>

<script>
    let plusBtn = document.querySelector('#plus');
    plusBtn.onclick = function() {
    
    
        // 1、获取 screen 的值
        let screen = document.querySelector('#screen');
        let val = screen.value;
        val = parseInt(val);

        // 2、将这个值 + 1
        val = val + 1;
        
        // 3、把新值写回去
        screen.value = val;
    }
</script>

Insert image description here


2. Manipulate the attributes of elements

2.1. Click to switch pictures

passdom object.Attribute nameYou can operate it

<img src="picture1.jpg" alt="">

<script>
    let img = document.querySelector('img');
    img.onclick = function() {
    
    
        console.log(img.src); // 打印 src 属性的内容
        
        if (img.src.indexOf('picture1.jpg') >= 0) {
    
    
            img.src = 'picture2.jpg';
        } else if (img.src.indexOf('picture2.jpg') >= 0) {
    
    
            img.src = 'picture1.jpg';
        }
    }
</script>

Insert image description here

What attributes can be written in an HTML tag can also be obtained through the DOM object in JS.

You can use console.dirthis method to print out all the attributes and values ​​of a DOM object.

console.dir(img);


3. Get/modify form element attributes

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

  • value: The value of input.
  • disabled: disable
  • checked: checkboxes will use
  • selected: The drop-down box will use
  • type: input type (text, password, button, file, etc.)

These properties are all properties exclusive to form elements.


3.1. Click counting

Use an input box to enter the initial value (integer). Each time the button is clicked, the value + 1

<input type="text" id="text" value="0">
<input type="button" id="btn" value='点我+1'>

    <script>
		var text = document.querySelector('#text');
		var btn = document.querySelector('#btn');
		
		btn.onclick = function () {
    
    
			var num = +text.value;
			console.log(num);
			num++;
			text.value = num;
		}
	</script>
  • input has an important attribute value, which determines the content of the form element
  • If it is an input box, value represents the content of the input box. Modifying this value will affect the interface explicitness; modifying this value on the interface will also affect the attributes in the code.
  • If it is a button, value represents the content of the button. You can use this to replace the text in the button

3.2. Switch button text

Assume this is a play button, switching between "play" - "pause"

<input type="button" value="播放">

<script>
    let input = document.querySelector('input');
    input.onclick = function() {
    
    
        if (input.value == '播放') {
    
    
            input.value = '暂停';
        } else if (input.value == '暂停') {
    
    
            input.value = '播放';
        }
    }
</script>

3.3. Select all/Cancel select all button

To achieve an all-select effect, it mainly operates the checked attribute of input.

  1. Click the Select All button to select all options
  2. As long as an option is canceled , the check state of the Select All button will be automatically canceled.
<input type="checkbox" id="all"> 全选 <br>
<input type="checkbox" class="girl"> 薛宝钗 <br>
<input type="checkbox" class="girl"> 林黛玉 <br>
<input type="checkbox" class="girl"> 王熙凤 <br>
<input type="checkbox" class="girl"> 贾探春 <br>

<script>
    // 1、获取元素
    let all = document.querySelector('#all');
    let girls = document.querySelectorAll('.girl'); // 

    // 2、给 all 注册点击事件
    all.onclick = function() {
    
    
        for (let i = 0; i < girls.length; i++) {
    
    
            // all.checked 就是 all 这个复选框的选中状态
            girls[i].checked = all.checked;
        }
    }

    // 3、针对每个 girl 注册点击事件,实现对于 all 的取消操作
    for (let i = 0; i < girls.length; i++) {
    
    
        girls[i].onclick = function() {
    
    
            all.checked = checkGirls(girls);
        }
    }

    function checkGirls(girls) {
    
    
        // 判断是不是所有的 girl 都被选中了
        for (let i = 0; i < girls.length; i++) {
    
    
            if (!girls[i].checked) {
    
    
                // 只要有一个是未选中,all 就是未选中状态
                return '';
            }
        }
        // 遍历完,所有都是选中状态,就让 all 也是选中状态
        return 'checked';
    }
</script>

4. Manipulate element styles

Essentially, it also operates on element attributes.

  1. styleCorresponds to inline style (write the style directly into style)
  2. className/ classListCorresponding to the internal style / external style, a / set of CSS class names are applied

4.1. Click to increase font size

let div = document.querySelector('div');
div.onclick = function() {
    
    
    // 1、获取当前的字体大小
    console.log(div.style.fontSize);   
}

Notice:

1. CSS is not case sensitive and generally does not use camel case. JS does not support spine as a variable name and cannot be used. All CSS properties are mapped according to the same rules

2. The fontSize currently obtained here is a string . If you want to add it, it must be converted into an integer
'20px' => parselnt => 20
parselnt. When converting, it will be converted from the beginning to the end , and the non-numeric character 'px' will be encountered. , the conversion stops

3. When modifying CSS attribute values, be sure to pay attention to the unit!! If the unit is inappropriate/missing, it will become invalid.

<div style="font-size: 20px;">这是一个文本</div>

<script>
    let div = document.querySelector('div');
    div.onclick = function() {
    
    
        // 1、获取当前的字体大小
        console.log(parseInt(div.style.fontSize));
        let fontSize = parseInt(div.style.fontSize);

        // 2、在当前字体大小的基础上,多增加 5px
        fontSize += 5;
        div.style.fontSize = fontSize + 'px';
    }
</script>

In HTML, the attribute representing the class name is class

But in JS, the attribute name becomes className/ classList, why not use classthis name directly?

classIt is also a keyword in JS (JS ES6 version and above also introduces the concept of class)

If there are many styles to be modified, it will be troublesome to modify them through style. You can modify them directly with the help of CSS classes.


4.2. Night mode

<style>
    .light {
    
    
        background-color: #fff;
        color: #000;
    }

    .dark {
    
    
        background-color: #000;
        color: #fff;
    }
</style>


<div class="light" style="height: 300px;">这是一段话</div>
<button>关灯</button>


<script>
    let div = document.querySelector('div');
    let button = document.querySelector('button');
    button.onclick = function() {
    
    
        if (div.className == 'light') {
    
    
            div.className = 'dark';
            button.innnerHTML = '开灯';
        } else if (div.className == 'dark') {
    
    
            div.className = 'light';
            button.innerHTML = '关灯';
        }
     }
</script>

4.4. Switch colors

Insert image description here
Deploy to tomcat \webapps\ROOT

    <style>
        div {
      
      
            width: 500px;
            height: 300px;
            font-size: 20px;
            font-weight: bold;
            text-align: center;
            line-height: 300px;
            
            background-image: url(f:/Photos/520.png);
            background-size: 100%, 100%;
        }

        .one {
      
      
            color: orange;
        }

        .two {
      
      
            color: green;
        }

        button {
      
      
            width: 150px;
            height: 50px;
            background-color: rgb(0, 128, 128);
            border-radius: 10px;
            border: none;
            outline: none;
        }

        button:active {
      
      
            background-color: #666;
        }
    </style>

    <div class="one">have a good day!</div><br>
    <button style="font-size: 17px;">orange</button>

    <script>
        let div = document.querySelector('div');
        let button = document.querySelector('button');
        button.onclick = function() {
      
      
            if (div.className == 'one') {
      
      
                div.className = 'two';
                button.innerHTML = 'green';
            } else if (div.className == 'two') {
      
      
                div.className = 'one';
                button.innerHTML = 'orange';
            }
        }
    </script>

5. Operation node

For element operations, it is actually to operate the attributes of the element (the element itself has not changed) .
For node operations, it is actually to add nodes/delete nodes.

5.1. Add new nodes

Divided into two steps:

  1. Create element node

  2. Insert element nodes into the dom tree

The first step is equivalent to giving birth to a baby, and the second step is equivalent to registering a household for the baby.

Create new node:

Use createElementthe method to create an element. The options parameter is not concerned yet.

<script>
    let newDiv = document.createElement('div'); // 创建标签
    newDiv.id = 'newDiv';
    newDiv.className = 'one';
    newDiv.innerHTML = 'hello';
    console.log(newDiv);
</script>

Insert image description here

The node created here is not hung on the dom tree , so it cannot be displayed on the browser page.

The above introduction only creates element nodes, you can also use:

  • createTextNode creates a text node

  • createComment creates a comment node

  • createAttribute creates an attribute node

We can mainly use createElement

Hang the node on the dom tree:

Use appendChildto insert a node into a node after the last child of the specified node.

<div class="container"></div>

<script>
    let newDiv = document.createElement('div'); // 创建标签
    newDiv.id = 'newDiv';
    newDiv.className = 'one';
    newDiv.innerHTML = 'hello';
    console.log(newDiv);

    let container = document.querySelector('.container');
    container.appendChild(newDiv);
</script>

Insert image description here

You can also use insertBefore to insert a node before the specified node.

  • var insertedNode = parentNode.insertBefore(newNode, referenceNode);
  • insertedNode inserted node (newNode)
  • parentNode The parent node of the newly inserted node
  • newNode is the node used for insertion
  • referenceNode newNode will be inserted before this node

If referenceNode is null then newNode will be inserted at the end of the child node.

Note: referenceNode reference node is not an optional parameter

<div class="container">
	<div>11</div>
	<div>22</div>
	<div>33</div>
	<div>44</div>
</div>

<script>
	var newDiv = document.createElement('div');
	newDiv.innerHTML = '我是新的节点';
	
	var container = document.querySelector('.container');
	console.log(container.children);
	container.insertBefore(newDiv, container.children[0]);
</script>

Insert image description here

Note 1: If a node is inserted twice, only the last one will take effect (equivalent to moving the element)

<div class="container">
	<div>11</div>
	<div>22</div>
	<div>33</div>
	<div>44</div>
</div>

<script>
	var newDiv = document.createElement('div');
	newDiv.innerHTML = '我是新的节点';

	var container = document.querySelector('.container');
	console.log(container.children);
	// 此处的 children 里有 4 个元素
	container.insertBefore(newDiv, container.children[0]);
	// 此处的 children 里有 5 个元素(上面新插了一个), 0 号元素是 新节点,
	// 1 号元素是 11, 2号节点是 22, 所以是插入到 22 之前.
	container.insertBefore(newDiv, container.children[2]);
</script>

Insert image description here

Note 2: Once a node is inserted, modifications to the node object can synchronously affect the content in the DOM tree.

<div class="container">
	<div>11</div>
	<div>22</div>
	<div>33</div>
	<div>44</div>
</div>

<script>
	var newDiv = document.createElement('div');
	newDiv.innerHTML = '我是新的节点';
	var container = document.querySelector('.container');
	console.log(container.children);
	container.insertBefore(newDiv, container.children[0]);
	// 插入完毕后再次修改 newDiv 的内容
	newDiv.innerHTML = '我是新节点2';
</script>

Insert image description here


5.2. Delete nodes

To delete a node, removeChildyou must
first get the parent node , and then get the child node to be deletedremoveChild , and you can delete it through

  • 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 the memory and can be added to other locations in the DOM tree at any time.
  • If the child node in the above example is not a child node of the element node, this method will throw an exception.
<div class="container"></div>

<button>删除 div</button>

<script>
    let newDiv = document.createElement('div'); // 创建标签
    newDiv.id = 'newDiv';
    newDiv.className = 'one';
    newDiv.innerHTML = 'hello';
    console.log(newDiv);

    let container = document.querySelector('.container');
    container.appendChild(newDiv);

    let button = document.querySelector('button');
    button.onclick = function() {
    
    
        container.removeChild(newDiv); // 前面已经获取了
    }
</script>

Insert image description here


5. Code cases

1. Guess the number

Insert image description here

How to generate 1 - 100 from the random decimal [0, 1) obtained by Math.random?
First *100, get the decimal between [0, 100). Then round down Math.floor, that is, directly discard the decimal part

<button id="resetBtn">重新开始一局游戏</button> <br>
<span>要猜的数字:</span>
<input type="text">
<button id="guessBtn"></button> <br>
<span>结果:</span> <span id="result"></span> <br>
<span>已经猜的次数:</span> <span id="guessCount">0</span>
    
<script>
    // 1、需要用到的元素
    let resetBtn = document.querySelector('#resetBtn');
    let input = document.querySelector('input');
    let guessBtn = document.querySelector('#guessBtn');
    let resultSpan = document.querySelector('#result');
    let guessCountSpan = document.querySelector('#guessCount');
    
    // 2、生成一个 1 - 100 的随机数
    let toGuess = Math.floor(Math.random() * 100) + 1;
    console.log(toGuess);

    // 3、实现点击 猜 按钮的逻辑
    guessBtn.onclick = function() {
    
    
        // 1) 读取 input 输入的内容,转成整数
        if (input.value == '') {
    
    
            return;
        }
        let curNum = parseInt(input.value);
        // 2) 判断大小 给出提示
        if (curNum < toGuess) {
    
    
            resultSpan.innerHTML = '低了';
            resultSpan.style.color = 'red';
        } else if (curNum > toGuess) {
    
    
            resultSpan.innerHTML = '高了';
            resultSpan.style.color = 'red';
        } else {
    
    
            resultSpan.innerHTML = '猜对了';
            resultSpan.style.color = 'green'               ;
        }
        // 3) 更新猜的次数
        let guessCount = parseInt(guessCountSpan.innerHTML);
        guessCountSpan.innerHTML = guessCount + 1;
    }

    // 4、实现 reset 操作,开始游戏
    resetBtn.onclick = function() {
    
    
        // 让页面刷新即可
        // location 是和 document 并列关系的对象,用来控制页面的链接/地址,通过 reload 操作就可以刷新页面
        location.reload();
    }
</script>

2. Confession wall

Insert image description here

<style>
    * {
      
      
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    .container {
      
      
        width: 100%;
    }

    h3 {
      
      
        text-align: center;
        padding: 30px 0; /* 上下内边距 20,左右为 0 */
        font-size: 24px;
    }

    p {
      
      
        text-align: center;
        color: #999;
        padding: 10px 0;
    }

    .row {
      
      
        width: 400px;
        height: 50px;
        margin: 0 auto;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    .row span {
      
      
        width: 60px;
        font-size: 20px;
    }

    .row input {
      
      
        width: 300px;
        height: 40px;
        line-height: 40px;
        font-size: 20px;
        text-indent: 0.5em;
        /* 去掉输入框的轮廓线 */
        outline: none;
    }

    .row #submit {
      
      
        width: 200px;
        height: 40px;
        font-size: 20px;
        line-height: 40px;
        margin: 0 auto;
        color: white;
        background-color: orange;
        /* 去掉边框 */
        border: none;
        border-radius: 10px;
    }

    /* 按下的效果 */
    .row #submit:active {
      
      
        background-color: grey;
    }
</style>

<div class="container">
    <h3>表白墙</h3>
    <p>输入后点击提示,会将信息显示在表格中</p>
    <div class="row">
        <span>谁:</span>
        <input type="text">
    </div>
    <div class="row">
        <span>对谁:</span>
        <input type="text">
    </div>
    <div class="row">
        <span>说:</span>
        <input type="text">
    </div>
    <div class="row">
        <button id="submit">提交</button>        
    </div>
</div>

<script>
    // 当用户点击 submit,就会获取 input 中的内容,把内容构造成一个 div,插入页面末尾
    let submitBtn = document.querySelector('#submit');
    submitBtn.onclick = function() {
      
      
        // 1、获取 2 个 input
        let inputs = document.querySelectorAll('input');
        let from = inputs[0].value;
        let to = inputs[1].value;
        let msg = inputs[2].value;
        if (from == '' || to == '' || msg == '') {
      
       // 用户还未填写完毕
            return;
        }
        // 2、生成一个新的 div,内容就是 input 中的内容,新的 div 加到页面中
        let div = document.createElement('div');
        div.innerHTML = from + ' 对 ' + to + ' 说 ' + msg;
        div.className = 'row'; // 应用 row 的样式
        let container = document.querySelector('.container');
        container.appendChild(div);
        // 3、清空之前输入框的内容
        for (let i = 0; i < inputs.length; i++) {
      
      
            inputs[i].value = '';
        }
    }
</script>

The confession wall program we just wrote uses some div.rows to save the messages we submitted. These div.rows are hung on the DOM tree and are in memory. They are easily lost once the page is refreshed/closed
. , at this time, the data previously saved in the memory is gone.

In order to solve the above problem of easy data loss, there are the following solutions:

  1. The submitted data can be saved locally in the browser (the browser provides a mechanism such as localStorage / indexDB, which can realize local storage). In essence, the data you want to save is saved to the disk of the current computer through the browser. Question
    : Only I can see it on my computer, but no one else can.

  2. The submitted data can be transmitted to the server through network communication and saved by the server.

    • The server is kept in memory
    • Server saved in file
    • The server saves it in the database

3. To-do items

Insert image description here

<style>
    * {
      
      
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    .container {
      
      
        width: 800px;
        margin: 0 auto;
        display: flex;
    }
    .todo,
    .done {
      
      
        width: 50%;
        height: 100%;
    }
    .container h3 {
      
      
        height: 50px;
        text-align: center;
        line-height: 50px;
        background-color: #333;
        color: #fff;
    }
    .nav {
      
      
        width: 800px;
        height: 100px;
        margin: 0 auto;
        display: flex;
        align-items: center;
    }
    .nav input {
      
      
        width: 600px;
        height: 50px;
    }
    .nav button {
      
      
        width: 200px;
        height: 50px;
        border: none;
        background-color: orange;
        color: #fff;
    }
    .row {
      
      
        height: 50px;
        display: flex;
        align-items: center;
    }
    .row input {
      
      
        margin: 0 10px;
    }
    .row span {
      
      
        width: 300px;
    }
    .row button {
      
      
        width: 50px;
        height: 40px;
    }
</style>

<div class="nav">
    <input type="text">
    <button>新建任务</button>
</div>
<div class="container">
    <div class="todo">
        <h3>未完成</h3>
        <div class="row">
            <input type="checkbox">
            <span>任务</span>
            <button>删除</button>
        </div>
    </div>
    <div class="done">
        <h3>已完成</h3>
    </div>
</div>

<script>
    // 一、实现新增任务
    let addTaskButton = document.querySelector('.nav button');
    addTaskButton.onclick = function () {
      
      
        // 1. 获取到任务内容的输入框
        let input = document.querySelector('.nav input');
        // 2. 获取到输入框内容
        let taskContent = input.value;
        // 3. 根据内容新建一个元素节点
        let row = document.createElement('div');
        row.className = 'row';
        let checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        let span = document.createElement('span');
        span.innerHTML = taskContent;
        let button = document.createElement('button');
        button.innerHTML = '删除';
        row.appendChild(checkbox);
        row.appendChild(span);
        row.appendChild(button);
        // 4. 把新节点插入到 todo 中
        let todo = document.querySelector('.todo');
        todo.appendChild(row);

        // 二、点击复选框后将元素放到 "已完成"
        //    在事件回调函数中使用 this 能够获取到当前处理事件的元素.
        //    通过 this.parentNode 属性能够获取到当前元素的父元素.
        //    点击 checkbox 时, 会先修改 value , 再触发点击事件
        
        // 修改 addTaskButton.onclick
        // 5. 给 checkbox 注册点击事件
        checkbox.onclick = function () {
      
      
            //
            var row = this.parentNode;
            // 注意! 是先触发 checked 为 true, 然后再调用 onclick 函数
            if (this.checked) {
      
      
                var target = document.querySelector('.done');
            } else {
      
      
                var target = document.querySelector('.todo');
            }
            target.appendChild(row);
        }

        // 三、点击删除按钮删除该任务
        // 6. 给删除按钮注册点击事件
        button.onclick = function () {
      
      
            let row = this.parentNode;
            let grandParent = row.parentNode;
            grandParent.removeChild(row);
        }
    }
</script>

Guess you like

Origin blog.csdn.net/qq_56884023/article/details/124914276