Introduction to JavaScript Basics 05

Table of contents

1. Operation node

1.1 New node

1.1.1. Create element nodes

1.1.2. Inserting nodes into the dom tree

1.2 Delete nodes

2.Code example: Guess the number

2.1 Expected effects

2.2 Code implementation

3. Code example: Confession wall

3.1 Expected effects

3.2 Create page layout

3.3 Adjust style

3.4 Implement submission

3.5 Implement the animation effect of clicking the button

4. Code example: To-do list

4.1 Expected effects

4.2 Create page layout

4.3 Implement page style

4.4 Implement page behavior

4.4.1 Implement new additions

4.4.2 After clicking the check box, place the element in "Complete"

4.4.3 Click the delete button to delete the task


1. Operation node

1.1 New node

Divided into two steps
1. Create element node
2. Insert element node into dom tree.
The first step is equivalent to giving birth to a baby, and the second step is equivalent to registering the baby.

1.1.1. Create element nodes

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

var element = document.createElement(tagName[, options]);

Code 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 was discovered that although a new div was created, the div was not displayed on the page. This is because the newly created node was not added to the DOM tree.

The above introduction only creates element nodes. You can also use:
        createTextNode to create text nodes
        createComment to create comment nodes
        createAttribute creates attribute nodes
We can mainly use createElement.

1.1.2. Inserting nodes into the dom tree

1) Use appendChild to insert the node after the last child of the specified node

element.appendChild(aChild)
<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>

2) Use insertBefore to insert the node before the specified node.

var insertedNode = parentNode.insertBefore(newNode, referenceNode);

insertedNode The inserted node (newNode)
parentNode The parent node of the newly inserted node
newNode is used Inserted node
referenceNode newNode will be inserted before this node
If referenceNode is null, 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>

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>

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>

1.2 Delete nodes

Use removeChild to delete child nodes

oldChild = element.removeChild(child);

child is the node to be deleted
element is the parent node of child
and 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, The method will throw an exception.

2.Code example: Guess the number

2.1 Expected effects

2.2 Code implementation

<button type="button" id="reset">重新开始一局游戏</button>
<br>
请输入要猜的数字:<input type="text" id="number">
<button type="button" id="button">猜</button>
<br>
已经猜的次数:<span id="count">0</span>
<br>
结果:<span id="result"></span>
<script>
  var inputE = document.querySelector("#number");
  var countE = document.querySelector("#count");
  var resultE = document.querySelector("#result");
  var btn = document.querySelector("#button");
  var resetBtn = document.querySelector("#reset");
  // 随机生成一个 1-100 的数字
  var guessNumber = Math.floor(Math.random() * 100) + 1// 0 - 1 之间的数
  var count = 0;
  // on: 当
  // click: 点击
  // 事件驱动(Event-Drive):只要真正发生了点击事件时,才执行该函数
  btn.onclick = function() {
    count++;
    countE.innerText = count;
    var userGuess = parseInt(inputE.value);
    if (userGuess == guessNumber) {
      resultE.innerText = "猜对了";
      resultE.style = "color: gray;";
   } else if (userGuess < guessNumber) {
      resultE.innerText = "猜小了";
      resultE.style = "color: blue;";
   } else {
      resultE.innerText = "猜大了";
      resultE.style = "color: red;";
   }
 };
  resetBtn.onclick = function() {
    guessNumber = Math.floor(Math.random() * 100) + 1
    count = 0;
    countE.innerText = count;
    resultE.innerText = "";
    inputE.value = "";
 }
</script>

3. Code example: Confession wall

3.1 Expected effects

3.2 Create page layout

Create confession wall.html

<h1>表白墙</h1>
<p>输入后点击提交, 会将信息显示在表格中</p>
<span>谁: </span>
<input type="text">
<span>对谁: </span>
<input type="text">
<span>说什么: </span>
<input type="text">
<input type="button" value="提交">

At this time the effect looks like

3.3 Adjust style

<div class="container">
  <h1>表白墙</h1>
  <p>输入后点击提交, 会将信息显示在表格中</p>
  <div class="row">
    <span>谁: </span>
    <input class="edit" type="text">
  </div>
  <div class="row">
    <span>对谁: </span>
比特就业课
     <input class="edit" type="text">
  </div>
  <div class="row">
    <span>说什么: </span>
    <input class="edit" type="text">
  </div>
  <div class="row">
    <input type="button" value="提交" class="submit">
  </div>
</div>
<style>
 * {
    margin: 0;
    padding: 0;
 }
  .container {
    width: 400px;
    margin: 0 auto;
 }
  h1 {
    text-align: center;
    padding: 20px 0;
 }
  p {
    color: #666;
    text-align: center;
    font-size: 14px;
    padding: 10px 0;
 }
  .row {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
 }
  span {
    width: 100px;
    line-height: 40px;
 }
  .edit {
    width: 200px;
    height: 30px;
 }
  .submit {
    width: 304px;
    height: 40px;
    color: white;
    background-color: orange;
    border: none;
 }

</style>

At this time the effect looks like

3.4 Implement submission

<script>
    //给点击按钮注册点击事件:
    var submit = document.querySelector('.submit');
    submit.onclick = function() {
        //获取到编辑框中的内容:
        var edit = document.querySelectorAll('.edit');
        var from = edit[0].value;
        var to = edit[1].value;
        var message = edit[2].value;
        console.log(from + "," + to + "," + message);
        if(from == "" || to == "" || message == "")
            return;
        //构造html元素:
        var row = document.createElement('div');
        row.className = 'row';
        row.innerHTML = from + '对' + to + '说:' + message;
        //把构造好的元素添加进去:
        var container = document.querySelector('.container');
        container.appendChild(row);
        //清理之前输入框中的内容:
        for(var i = 0; i < 3; ++i) {
            edit[i].value = ''; 
        }
    }
</script>

3.5 Implement the animation effect of clicking the button

You need to use a pseudo-class selector.
There are many types of pseudo-class selectors. :active here means selecting the pressed button

.submit:active {
  background-color: #666;
}

4. Code example: To-do list

4.1 Expected effects

4.2 Create page layout

Create to-do.html

<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>

4.3 Implement page style

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .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: 190px;
            height: 50px;
            border: none;
            background-color: orange;
            color: #fff;
            margin-left: 5px;
        }
        .row {
            height: 50px;
            display: flex;
            align-items: center;
        }
        .row input {
            margin: 0 10px;
        }
        .row span {
            width: 300px;
        }
        .row button {
            width: 50px;
            height: 40px;
        }
    </style>

4.4 Implement page behavior

4.4.1 Implement new additions

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

4.4.2 After clicking the check box, place the element in "Complete"

// 修改 addTaskButton.onclick
addTaskButton.onclick = function () {
// 上方的部分不变...
 
  // 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);
 }
}

Note:
Use this in the event callback function to get the element currently processing the event.
You can get the current element through the this.parentNode property The parent element of the element.
When the checkbox is clicked, the value will be modified first, and then the click event will be triggered.

4.4.3 Click the delete button to delete the task

// 修改 addTaskButton.onclick
addTaskButton.onclick = function () {
// 上方的部分不变...
  // 6. 给删除按钮注册点击事件
  button.onclick = function () {
    var row = this.parentNode;
    var grandParent = row.parentNode;
    grandParent.removeChild(row);
 }
}

Guess you like

Origin blog.csdn.net/qq_65307907/article/details/133816216