• 【web APIs】4、(学习笔记)有案例!


    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


    前言

    • 能够插入、删除和替换元素节点
    • 能够依据元素节点关系查找节点

    一、日期对象

    ECMAScript 中内置了获取系统时间的对象 Date,使用 Date 时与之前学习的内置对象 console 和 Math 不同,它需要借助 new 关键字才能使用。

    实例化

      // 1. 实例化
      // const date = new Date(); // 系统默认时间
      const date = new Date('2020-05-01') // 指定时间
      // date 变量即所谓的时间对象
    
      console.log(typeof date)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    方法

     // 1. 实例化
    const date = new Date();
    // 2. 调用时间对象方法
    // 通过方法分别获取年、月、日,时、分、秒
    const year = date.getFullYear(); // 四位年份
    const month = date.getMonth(); // 0 ~ 11
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.getFullYear 获取四位年份

    2.getMonth 获取月份,取值为 0 ~ 11

    3.getDate 获取月份中的每一天,不同月份取值也不相同

    4.getDay 获取星期,取值为 0 ~ 6

    5.getHours 获取小时,取值为 0 ~ 23

    6.getMinutes 获取分钟,取值为 0 ~ 59

    7.getSeconds 获取秒,取值为 0 ~ 59

    二、时间戳

    时间戳是指1970年01月01日00时00分00秒起至现在的总秒数或毫秒数,它是一种特殊的计量时间的方式。

    注:ECMAScript 中时间戳是以毫秒计的。

        // 1. 实例化
      const date = new Date()
      // 2. 获取时间戳
      console.log(date.getTime())
    // 还有一种获取时间戳的方法
      console.log(+new Date())
      // 还有一种获取时间戳的方法
      console.log(Date.now())
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    获取时间戳的方法,分别为 getTime 和 Date.now 和 +new Date()

    三、DOM 节点

    回顾之前 DOM 的操作都是针对元素节点的属性或文本的,除此之外也有专门针对元素节点本身的操作,如插入、复制、删除、替换等。

    插入节点

    在已有的 DOM 节点中插入新的 DOM 节点时,需要关注两个关键因素:首先要得到新的 DOM 节点,其次在哪个位置插入这个节点。

    如下代码演示:

    <body>
      <h3>插入节点h3>
      <p>在现有 dom 结构基础上插入新的元素节点p>
      <hr>
      
      <div class="box">div>
      
      <button class="btn">插入节点button>
      <script>
        // 点击按钮,在网页中插入节点
        const btn = document.querySelector('.btn')
        btn.addEventListener('click', function () {
          // 1. 获得一个 DOM 元素节点
          const p = document.createElement('p')
          p.innerText = '创建的新的p标签'
          p.className = 'info'
          
          // 复制原有的 DOM 节点
          const p2 = document.querySelector('p').cloneNode(true)
          p2.style.color = 'red'
    
          // 2. 插入盒子 box 盒子
          document.querySelector('.box').appendChild(p)
          document.querySelector('.box').appendChild(p2)
        })
      script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    结论:

    • createElement 动态创建任意 DOM 节点

    • cloneNode 复制现有的 DOM 节点,传入参数 true 会复制所有子节点

    • appendChild 在末尾(结束标签前)插入节点

    • insertBefore 在父节点中任意子节点之前插入新节点

    删除节点

    删除现有的 DOM 节点,也需要关注两个因素:首先由父节点删除子节点,其次是要删除哪个子节点。

    <body>
      
      <button>删除节点button>
      <ul>
        <li>HTMLli>
        <li>CSSli>
        <li>Web APIsli>
      ul>
    
      <script>
        const btn = document.querySelector('button')
        btn.addEventListener('click', function () {
          // 获取 ul 父节点
          let ul = document.querySelector('ul')
          // 待删除的子节点
          let lis = document.querySelectorAll('li')
    
          // 删除节点
          ul.removeChild(lis[0])
        })
      script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    结论:removeChild 删除节点时一定是由父子关系。

    查找节点

    DOM 树中的任意节点都不是孤立存在的,它们要么是父子关系,要么是兄弟关系,不仅如此,我们可以依据节点之间的关系查找节点。

    父子关系
    • childNodes 获取全部的子节点,回车换行会被认为是空白文本节点
    • children 只获取元素类型节点
    • parentNode 获取父节点,以相对位置查找节点,实际应用中非常灵活。
    兄弟关系
    • previousSibling 获取前一个节点,以相对位置查找节点,实际应用中非常灵活。
    • nextSibling 获取后一个节点,以相对位置查找节点,实际应用中非常灵活。

    四、案例举例

    1.显示格式化时间

    年月日时分秒的获取

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
      <style>
        div {
          width: 300px;
          height: 40px;
          border: 1px solid pink;
          text-align: center;
          line-height: 40px;
        }
      style>
    head>
    
    <body>
      <div>div>
      <script>
        const div = document.querySelector('div')
        function getMyDate() {
          const date = new Date()
          let h = date.getHours()
          let m = date.getMinutes()
          let s = date.getSeconds()
          h = h < 10 ? '0' + h : h
          m = m < 10 ? '0' + m : m
          s = s < 10 ? '0' + s : s
          return `今天是: ${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}${h}:${m}:${s}`
        }
    
        div.innerHTML = getMyDate()
        setInterval(function () {
          div.innerHTML = getMyDate()
        }, 1000)
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    2.倒计时

    秒数转化为*时 *分 *秒
    00:00:00的表示形式
    实时更新并显示时间

    <script>
        const countdown = document.querySelector('.countdown')
        countdown.style.backgroundColor = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`
        const next = document.querySelector('.next')
        next.innerHTML = `今天是${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}`
    
        function tran() {
          //(约定时间-当前时间)/1000
          const now = +new Date()   //当前
          const last = +new Date('2024-02-27 23:30:00')
          const re = (last - now) / 1000
    
          //秒转化为**时**分**秒
          let m = parseInt(re / 60 % 60)            //parseInt
          let h = Math.floor(re / 60 / 60 % 24)
          let s = parseInt(re % 60)
    
          //判断是否大于10
          h = h >= 10 ? h : '0' + h
          m = m >= 10 ? m : '0' + m
          s = s >= 10 ? s : '0' + s
    
          document.querySelector('#hour').innerHTML = h
          document.querySelector('#minutes').innerHTML = m
          document.querySelector('#second').innerHTML = s
        }
        tran()
        setInterval(tran, 1000)    //这里tran不需要括号
    
    
    
      script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3.学成在线首页

    内容替换,createElement,appendChild的使用

    DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>学车在线首页title>
        <link rel="stylesheet" href="./css/style.css">
        <style>
    
        style>
    head>
    
    <body>
    
        
        <div class="box w">
            <div class="box-hd">
                <h3>精品推荐h3>
                <a href="#">查看全部a>
            div>
            <div class="box-bd">
                <ul class="clearfix">
                    
    
    
                ul>
            div>
        div>
        <script>
            // 1. 重构  
            let data = [
                {
                    src: 'images/course01.png',
                    title: 'Think PHP 5.0 博客系统实战项目演练',
                    num: 1125
                },
                {
                    src: 'images/course02.png',
                    title: 'Android 网络动态图片加载实战',
                    num: 357
                },
                {
                    src: 'images/course03.png',
                    title: 'Angular2 大前端商城实战项目演练',
                    num: 22250
                },
                {
                    src: 'images/course04.png',
                    title: 'Android APP 实战项目演练',
                    num: 389
                },
                {
                    src: 'images/course05.png',
                    title: 'UGUI 源码深度分析案例',
                    num: 124
                },
                {
                    src: 'images/course06.png',
                    title: 'Kami2首页界面切换效果实战演练',
                    num: 432
                },
                {
                    src: 'images/course07.png',
                    title: 'UNITY 从入门到精通实战案例',
                    num: 888
                },
                {
                    src: 'images/course08.png',
                    title: 'Cocos 深度学习你不会错过的实战',
                    num: 590
                },
            ]
            const ul = document.querySelector('.box-bd ul')            //('父节点类名  ul')
            for (let i = 0; i < data.length; i++) {
                const li = document.createElement('li')
                li.innerHTML = `
                    
                        ${data[i].src} alt="">
                        

    ${data[i].title}

    高级${data[i].num}人在学习
    `
    ul.appendChild(li) }
    script> body> html>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106

    4.学生就业信息表

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <title>学生信息管理title>
      <link rel="stylesheet" href="css/index.css" />
    head>
    
    <body>
      <h1>新增学员h1>
      <form class="info" autocomplete="off">
        姓名:<input type="text" class="uname" name="uname" />
        年龄:<input type="text" class="age" name="age" />
        性别:
        <select name="gender" class="gender">
          <option value="">option>
          <option value="">option>
        select>
        薪资:<input type="text" class="salary" name="salary" />
        就业城市:<select name="city" class="city">
          <option value="北京">北京option>
          <option value="上海">上海option>
          <option value="广州">广州option>
          <option value="深圳">深圳option>
          <option value="曹县">曹县option>
        select>
        <button class="add">录入button>
      form>
    
      <h1>就业榜h1>
      <table>
        <thead>
          <tr>
            <th>学号th>
            <th>姓名th>
            <th>年龄th>
            <th>性别th>
            <th>薪资th>
            <th>就业城市th>
            <th>操作th>
          tr>
        thead>
        <tbody>
          
        tbody>
      table>
      <script>
        //1.获取元素
        const uname = document.querySelector('.uname')
        const age = document.querySelector('.age')
        const gender = document.querySelector('.gender')
        const salary = document.querySelector('.salary')
        const city = document.querySelector('.city')
        const info = document.querySelector('.info')
        const items = document.querySelectorAll('[name]')
    
        let arr = []
        //form提交事件(数据更新渲染函数)
        info.addEventListener('submit', function (e) {
          //阻止默认行为
          e.preventDefault()
          //判断内容是否为空
          for (let i = 0; i < items.length; i++) {
            if (items[i].value === '') {      //
              return alert('输入不能为空')
            }
          }
    
          //数据替换
          const data = {
            stuId: arr.length + 1,
            uname: uname.value,
            age: age.value,
            gender: gender.value,
            salary: salary.value,
            city: city.value,
          }
          arr.push(data)
        
          //新数据渲染到下面表格
          render()
    
          //清空text填写原有数据
          this.reset()
        })
     function render() {
          // 先清空tbody 以前的行 ,把最新数组里面的数据渲染完毕 
        tbody.innerHTML = ''
          // 遍历arr数组
        for (let i = 0; i < arr.length; i++) {
            // 生成 tr 
            const tr = document.createElement('tr')
            tr.innerHTML = `
              ${arr[i].stuId}
              ${arr[i].uname}
              ${arr[i].age}
              ${arr[i].gender}
              ${arr[i].salary}
              ${arr[i].city}
              
                ${i}>删除
              
            `
            // 追加元素  父元素.appendChild(子元素)
            tbody.appendChild(tr)
          }
        }
    
    
        //del删除事件(借助自定义属性)
        const tbody = document.querySelector('tbody')
        tbody.addEventListener('click', function (e) {
          if (e.target.tagName === 'A') {
            arr.splice(e.target.dataset.id, 1)         //arr  render里面的new_data是添加在tbody里面
            localStorage.removeItem('data', JSON.stringify(arr[e.target.dataset.id]))
            render()       
          }
        })
    
      script>
    
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
  • 相关阅读:
    数据分析实战 | 逻辑回归——病例自动诊断分析
    基于 ARM+FPGA+AD平台的多类型同步信号采集仪开发及试验验证(一)
    代码随想录算法训练营Day 55 || 583. 两个字符串的删除操作、72. 编辑距离
    力扣3、无重复字符串
    nuxt3:我们开始吧!
    企业级低代码开发效率变革赋能业务增长
    逐鹿人形机器人,百度、腾讯、小米卷起来
    通过WSL2搭建Pytorch1.10+CUDA11.4+NVIDIA Driver深度学习框架
    CCC联盟——UWB MAC(一)
    Banana Pi BPI-W3(ArmSoM-W3) RK3588编解码之MPP环境配置
  • 原文地址:https://blog.csdn.net/qq_46644680/article/details/136328172