两种本地存储,复杂数据转为字符串或者相反,自定义属性加固定属性,重绘和回流,事件解绑,事件流动,高阶函数,字符串方法和数组方法

134 阅读2分钟

1.locaStorage-本地存储

1649984511322.png

本地存储的四个API

localStorage.setItem():储存

localStorage.getItem():获取

localStorage.removeItem():删除一个

localStorage.clear():清空全部

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>04-本地存储-localStorage.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <script>
      // 存储日期
      // localStorage.setItem("自定义",值-必须是字符串的格式)
      // localStorage.setItem("date","二〇二二年四月十五日 09:06:48")

      // 获取它
      const date=localStorage.getItem("date");
      console.log(date);
    </script>
  </body>
</html>

2.将数组(复杂类型数据)转为字符串和将字符串转为数组

1649992005486.png

JSON.stringify():将数组转为字符串

JSON.parse():将字符串转为数组

3.sessionStorage-本地存储

它的用法和 localStorage 用法一样

​ 区别只有一个

​ sessionStorage 关闭页面后 数据就丢失

​ localStorage 除非是用户主动删除 否则一直存在 直到天荒地老

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>11-sessionStorage.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <script>
      /* 
      本地存储的技术 sessionStorage  会话(打开页面到关闭页面之间过程 一次会话  ajax node)存储
      登录的时候 
      它的用法和 localStorage 用法一样 
      区别只有一个 
      sessionStorage 关闭页面后 数据就丢失 
      localStorage 除非是用户主动删除 否则一直存在 直到天荒地老
       */

      //  存数据
      // sessionStorage.setItem("ss",123);
      //  取数据
      // console.log(sessionStorage.getItem("ss"));
      // 删除一个
      // sessionStorage.removeItem("ss")
      // 清空
      // sessionStorage.clear();
    </script>
  </body>
</html>

4.自定义属性的两种方法

标签的属性 有两种分为

1 固有属性 比如 id href src 点语法的方式获取和设置 方便

2 自定义属性

​ 1 随机自己瞎命名

          <a  abc="123" >  

​ 获取 (getAttribute) 设置 setAttribute(key,value) 删除 removeAttribute(key)

​ 2 h5建议 data- xxx

          <a  data-abc="123" >  

​ 获取(a.dataset.abc) 设置(a.dataset.abc=456);

3 最强大是 (getAttribute) setAttribute removeAttribute

​ 上述的这个方式,可以获取到任意的属性(固有属性和h5建议的自定义属性)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>12-元素属性.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <a data-index="0" id="nav" href="http://www.baidu.com" hello="no" aa="bb" >跳转</a >

    <script>
      // 获取 dom元素的固有属性  通过点语法来获取
      const a = document.querySelector('a');
      // 获取固有属性
      // console.log(a.href);
      // console.log(a.id);

      // 直接修改
      // a.href="http://www.qq.com";
      // a.id="top";

      // 自定义属性 不能直接通过点语法来获取和设置
      // 获取 getAttribute("属性名")
      // console.log(a.hello);
      // console.log(a.aa);
      // console.log( a.getAttribute("hello") );
      // console.log( a.getAttribute("aa") );

      // 设置 setAttribute(key,value)
      // a.setAttribute("hello","123");

      // 删除掉属性 removeAttribute(key)
      // a.removeAttribute("hello");

      //  自定义属性 -> h5建议的 自定义属性
      // 属性的时候 data-xxx 开头
      //  获取的时候  a.dataset.xxx
      //  设置  a.dataset.index = 3;

      // console.log(a.dataset.index);
      // a.dataset.index = 3;

      /* 
      
      小结 
      标签的属性 有两种分为
      1 固有属性  比如 id href src     点语法的方式获取和设置 方便
      2 自定义属性
        1 随机自己瞎命名  
          <a  abc="123" >  
            获取 (getAttribute) 设置 setAttribute(key,value)  删除   removeAttribute(key)
        2 h5建议 data- xxx
          <a  data-abc="123" >  
            获取(a.dataset.abc)  设置(a.dataset.abc=456);
      3 最强大是  (getAttribute)  setAttribute removeAttribute 
            上述的这个方式,可以获取到任意的属性(固有属性和h5建议的自定义属性)
            <a data-index="0" id="nav" href="http://www.baidu.com" hello="no" aa="bb" >跳转</a >
      */
    //  console.log( a.getAttribute("data-index") );
    //  console.log( a.getAttribute("id") );
    //  console.log( a.getAttribute("href") );
    //  console.log( a.getAttribute("hello") );
    //  console.log( a.getAttribute("aa") );
    </script>
  </body>
</html>

5.自定义属性演示

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>13-自定义属性使用演示.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <ul></ul>
    <script>
      // 根据数组 渲染出li标签 点击li标签的时候  根据它对应的颜色 设置到 我body标签背景中

      // 数组
      let arr = [
        { price: '100', title: '去旅游', color: 'yellow' },
        { price: '200', title: '去读书', color: 'red' },
        { price: '300', title: '去吃饭', color: 'blue' },
      ];

      const ul = document.querySelector('ul');
      let html = ``;
      for (let index = 0; index < arr.length; index++) {
        html += `<li data-price="${arr[index].price}" data-color="${arr[index].color}" >${arr[index].title}</li>`;
      }
      ul.innerHTML = html;

      // 事件委托
      ul.addEventListener('click', function (event) {
        // 当前点击的是li标签
        if (event.target.nodeName === 'LI') {
          // 设置body标签的背景颜色  等于什么  =  等于当前被点击的元素(li) 身上的自定义属性 data-color
          // document.body.style.backgroundColor = event.target.dataset.color;
          document.body.style.backgroundColor =
            event.target.getAttribute('data-color');
          // alert(
          //   // `你想要去做的事情,要花这么多钱哦 ${event.target.dataset.price}`
          // );
        }
      });
    </script>
  </body>
</html>

6.重绘和回流

1649996743965.png

1649996962100.png

1649997080566.png

1649997221836.png

7.事件绑定-取消绑定

1 addEventListener 可以绑定多个同名事件

2 removeEventListener 可以取消对应的事件类型和事件处理函数

3 无法取消 addEventListener 事件 对应的匿名函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>15-事件绑定-取消绑定.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <button>点击我 输出时间</button>
    <script>
        // const btn = document.querySelector('button');

        // // 普通函数
        // function func() {
        //   console.log('2022-04-15 14:32:26');
        // }
        // function func2() {
        //   console.log("func2");
        // }

        // // 绑定事件
        // btn.addEventListener('click', func);

        // // addEventListener 可以绑定多个同名事件
        // btn.addEventListener('click', func2);

        // setTimeout(function () {
        //   // 取消这个事件绑定
        //   btn.removeEventListener('click', func);
        // }, 5000);
        /* 
        1 addEventListener 可以绑定多个同名事件
        2 removeEventListener 可以取消对应的事件类型和事件处理函数
  
        3 无法取消 addEventListener 事件 对应的匿名函数       
         */
        const btn = document.querySelector("button");
        btn.addEventListener("click", function () {
            console.log("你好");
        })

        //  想要取消 这个 输出你好的行为
        btn.removeEventListener("click",???);

    </script>
</body>
</html>

8.字符串方法

1 转大写 toUpperCase()

2 转小写 toLowerCase()

3 转数组 str.split('') 按照什么来分割你的字符串变成数组,引号中间要加个空格,放减号是一个引号包着全部

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>17-字符串方法.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <script>
        // 我们在实际开发过程中,有很多需求要针对字符串做处理
        // js 帮我们封装了很多大量和实用 字符串方法
        // 先介绍一些

        // 转大写 转小写。
        // let msg = 'HELLODFDFDFDFDFD';

        // 广告 msg 大写
        // msg="HELLO";// 搞定  楼下大妈也会!!!  low 低级 不堪入目
        // console.log(msg.toUpperCase());

        // 转小写
        // console.log(msg.toLowerCase()); //转成小写

        // 字符串和数组很相似
        // 能不能把字符串 转成数组?
        const str = "abcdefg"; //=> ["a","b","c","d","e","f","g"]
      // // split("")   分割
      // console.log(str.split(""));
      // const str = 'a-b-c-d-e-f-g'; // ["a","b","c","d","e","f","g"]
      // console.log(str.split('-'));

      // console.dir(str);

        /*
        1 转大写  toUpperCase()
  
        2 转小写 toLowerCase()
  
        3 转数组 str.split('') 按照什么来分割你的字符串变成数组,引号中间要加个空格,放减号是一个引号包着全部
         */
    </script>
</body>

</html>

9.数组方法

console.log(arr.join('')); // join 数组转字符串

console.log(arr.join('-')); // a-b-c-d 数组转字符串

将两个数组合并成一个数组

console.log(arr1.concat(arr2));

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>18-数组方法.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <script>
        // 数组 补充 常用
        //
        // const arr = ['a', 'b', 'c', 'd'];

        // console.log(arr.join('')); // join 数组转字符串
        // console.log(arr.join('-')); // a-b-c-d 数组转字符串

        // 连接  数组和数组之间连接
        // const arr1 = ['1', '2', '3'];
        // const arr2 = ['a', 'b', 'c'];
        // 将两个数组合并成一个数组
        // console.log(arr1.concat(arr2));

        //字符串也有一个 concat 也是表示合并
        const str1 = '123';
        const str2 = 'abc';
        // console.log(str1.concat(str2));// 很少用  有什么用? 当你的键盘 + 键坏  使用它 
        console.log(str1 + str2); // 更加简单好理解
    </script>
</body>

</html>

10.事件流动

事件流动 3个阶段
1 最重要的冒泡阶段 2 知道 捕获阶段 addEventListener 第三个参数 true|false 来进行切换 3 目标阶段 了,那个最底层就是处于目标阶段

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>16-事件流动.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      div{
        width: 300px;
        height: 300px;
        padding: 20px;
        overflow: hidden;
      }
      .a{
        background-color: red;
      }
      .b{
        background-color: salmon;
      }
      .c{
        background-color: seagreen;
      }
    </style>
  </head>
  <body>
    <div class="a">爷爷
      <div class="b">爸爸
        <div class="c">儿子</div>
      </div>
    </div>
    <script>
      /* 
      事件流动  3个阶段  
      1 最重要的冒泡阶段
      2 知道  捕获阶段 
        addEventListener 第三个参数  true|false 来进行切换
      3 目标阶段 了解一下 

       */
      const a=document.querySelector(".a");
      const b=document.querySelector(".b");
      const c=document.querySelector(".c");
      a.addEventListener("click",function () {
        console.log("爷爷");
      })
      b.addEventListener("click",function () {
        // 这个c 是最底层的元素 
        console.log("爸爸");
      })
      c.addEventListener("click",function () {
        // 这个c 是最底层的元素 
        console.log("儿子 目标阶段");
      })
    </script>
  </body>
</html>

11.if简写

if 对代码 做隐式转换 转换成布尔类型

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>09-if简写.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <script>
        let abc = null;
        // let abc = undefined;
        // let abc = "";
        // let abc = 0;
        // let abc = false;
        // let abc = NaN;
        // if 对代码 做隐式转换  转换成布尔类型 
        if (abc) {
            console.log(1);
        } else {
            console.log(2);
        }
    </script>
</body>

</html>

12.高阶函数

就是将另一个函数当参数用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>14-高阶函数.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <button>按钮</button>
    <script>
        /*
        在培训阶段, 高阶函数的应用 在react阶段(培训过程最后一个阶段) 大量的应用
        1 现在讲  会忘记 (必然)
        2 先讲 老师会再复习
        3 有什么用
          现在的我们的水平太低  还没有到封装代码的程度 所以没有用
  
        高阶函数
        把一个函数 看成是个普通数据,应用在 参数 或者返回值  技术
         */

      //  function f1(callback) {
      //    callback();
      //  }

      //  function f2() {
      //    console.log("我就是高阶函数");
      //  }

      //  f1(f2);// f2 当成是一个普通的参数来使用(形参来使用)

      // setInterval(f2,1000);// 把f2 当成是一个普通参数  传递给别人使用

      //  const btn=document.querySelector("button");
      //  btn.addEventListener("click",f2);// f2 也是高阶函数

      // function getIndex() {
      //   let index=0;
      //   return function () {
      //       index++;
      //       console.log(index);
      //   }
      // }
      // const ff=getIndex();
      // ff();

    </script>
</body>

</html>

就业薪资-本地储存案例

就是给就业薪资那个案例用上本地储存,这样刷新数据都还在

<!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>08-综合案例-模版</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      a {
        text-decoration: none;
        color: #721c24;
      }
      h1 {
        text-align: center;
        color: #333;
        margin: 20px 0;
      }
      table {
        margin: 0 auto;
        width: 800px;
        border-collapse: collapse;
        color: #004085;
      }
      th {
        padding: 10px;
        background: #cfe5ff;

        font-size: 20px;
        font-weight: 400;
      }
      td,
      th {
        border: 1px solid #b8daff;
      }
      td {
        padding: 10px;
        color: #666;
        text-align: center;
        font-size: 16px;
      }
      tbody tr {
        background: #fff;
      }
      tbody tr:hover {
        background: #e1ecf8;
      }
      .info {
        width: 900px;
        margin: 50px auto;
        text-align: center;
      }
      .info input {
        width: 80px;
        height: 25px;
        outline: none;
        border-radius: 5px;
        border: 1px solid #b8daff;
        padding-left: 5px;
      }
      .info button {
        width: 60px;
        height: 25px;
        background-color: #004085;
        outline: none;
        border: 0;
        color: #fff;
        cursor: pointer;
        border-radius: 5px;
      }
      .info .age {
        width: 50px;
      }
    </style>
  </head>

  <body>
    <h1>新增学员</h1>
    <div class="info">
      姓名:<input type="text" class="uname" /> 年龄:<input
        type="text"
        class="age"
      />
      性别:
      <select name="gender" id="" class="gender">
        <option value="男"></option>
        <option value="女"></option>
      </select>
      薪资:<input type="text" class="salary" /> 就业城市:<select
        name="city"
        id=""
        class="city"
      >
        <option value="北京">北京</option>
        <option value="上海">上海</option>
        <option value="广州">广州</option>
        <option value="深圳">深圳</option>
        <option value="曹县">曹县</option>
      </select>
      <button class="add">录入</button>
    </div>

    <h1>就业榜</h1>
    <table>
      <thead>
        <tr>
          <th>学号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>薪资</th>
          <th>就业城市</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- <tr>
          <td>1</td>
          <td>这是名称</td>
          <td>这是年龄</td>
          <td>这是性别</td>
          <td>这是工资</td>
          <td>这是所在城市</td>
          <td>
            <a href="javascript:" class="del">删除</a>
          </td>
        </tr> -->
      </tbody>
    </table>
    <script>
      // 1.1 定义数组 负责存放表格要显示的数据
      // 获取本地存储中的数组(字符串格式)  转成 数组格式

      // 第一次打开页面的时候 ,本地存储里面会有数据吗

      const strArr = localStorage.getItem('arr');
      let arr = [];
      if (strArr) {
        // 有值 转成数组
        arr = JSON.parse(strArr);
      } else {
        arr = [];
      }
      const tbody = document.querySelector('tbody');
      // 2  给 录入绑定点击事件
      const add = document.querySelector('.add');
      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');

      // 1.2 根据数组渲染页面
      renderTableByArr();

      // 2  按钮绑定点击事件
      add.addEventListener('click', function () {
        // 2.1 创建一个新的对象 把表单数据都合并到对象中
        const data = {
          // 学号
          id: Date.now(),
          // 姓名
          uname: uname.value,
          // 年龄
          age: age.value,
          // 性别
          gender: gender.value,
          // 薪资
          salary: salary.value,
          // 就业城市
          city: city.value,
        };

        // 老师打了一个 断点 来验证 上面的代码 没有写错
        // 2.2 给数组插入新的元素
        arr.push(data);

        // 把数组转成 字符串
        const strArr = JSON.stringify(arr);
        // 存一份到本地存储中
        localStorage.setItem('arr', strArr);

        // 2.3 数组发生改变  重新调用渲染页面的函数
        renderTableByArr();

        // 2.4 表单数据清空
        uname.value = '';
        age.value = '';
        gender.value = '男';
        salary.value = '';
        city.value = '北京';
      });

      // 3 tbody绑定点击事件,同时判断被点击的是不是 del 删除标签
      tbody.addEventListener('click', function (event) {
        // 3.1 判断当前点击的是不是a标签
        if (event.target.nodeName === 'A') {
          // <a data-index="2" href="javascript:" class="del">删除</a>

          // 获取到a标签 上存放的 index
          // event.target =  a标签的dom元素
          // console.dir(event.target.dataset.index)
          const index = event.target.dataset.index;

          // 3.3 执行数组删除元素
          arr.splice(index, 1);

          // 把数组转成 字符串
          const strArr = JSON.stringify(arr);
          // 存一份到本地存储中
          localStorage.setItem('arr', strArr);

          // 3.4 调用根据数组渲染页面的函数
          renderTableByArr();
        }
      });
      // 根据数组渲染表格
      function renderTableByArr() {
        let html = ``;
        for (let index = 0; index < arr.length; index++) {
          html += `
         <tr>
          <td>${arr[index].id}</td>
          <td>${arr[index].uname}</td>
          <td>${arr[index].age}</td>
          <td>${arr[index].gender}</td>
          <td>${arr[index].salary}</td>
          <td>${arr[index].city}</td>
          <td>
            <a data-index="${index}" href="javascript:" class="del">删除</a>
          </td>
        </tr>
         `;
        }

        // 把生成的tr插入到 tbody中
        tbody.innerHTML = html;
      }
    </script>
  </body>
</html>

**