前端css、js、bootstrap、vue2.x、ajax查漏补缺(1)

学到的总是忘,遇到了就随手过来补一下

1.【JS】innerHTML

  • innerHTML属性允许更改HTML元素的内容
  • 可以解析HTML标签

2.【CSS】display: none

  • 设置元素不可见,不占空间,约等于将元素删除一样,只是源代码还存在

3.【CSS】行内样式

4.【JS】DOM修改节点背景颜色

document.getQuerySelector('#app').style.backgroundColor = red;

5.【JS】数组的filter() 过滤方法,创建一个新数组

  • 根据形参条件生成新的数组,不会对原数组进行改变
  • 形参满足的项才会通过,不满足则被过滤

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建一个Vue实例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/mhDoLbDldZc3qpsJHpLogda//BVZbgYuw6kof4u2FrCedxOtgRZDTHgHUhOCVim" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div id="app">
            <ul>
                <li v-for="(item, index) in bookList">
                    <span>{{item.name}}</span>
                    <span>{{item.author}}</span>
                    <button @click="delBookList(item.id)">删除</button>
                </li>
            </ul>
        </div>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data:{
                bookList:[
                    {id: 1, name: '《西游记》', author: '吴承恩'},
                    {id: 2, name: '《水浒传》', author: '施耐庵'},
                    {id: 3, name: '《三国演义》', author: '罗贯中'},
                    {id: 4, name: '《红楼梦》', author: '曹雪芹'}
                ]
            },
            methods:{
                delBookList(id){
                    this.bookList = this.bookList.filter((item) => {return item.id != id})
                }
            }
        })
    </script>
</body>
    
</html>

6.【JS】unshift()向数组的开头加元素(push()向结尾)

<!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" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input v-model="todoName"  placeholder="请输入任务" class="new-todo" />
    <button @click="add" class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{{ index + 1 }}.</span> <label>{{ item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 -->
  <footer class="footer">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> 2 </strong></span>
    <!-- 清空 -->
    <button class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  // 添加功能
  // 1. 通过 v-model 绑定 输入框 → 实时获取表单元素的内容
  // 2. 点击按钮,进行新增,往数组最前面加 unshift
  const app = new Vue({
    el: '#app',
    data: {
      todoName: '',
      list: [
        { id: 1, name: '跑步一公里' },
        { id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      del (id) {
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
      },
      add () {
        if (this.todoName.trim() === '') {
          alert('请输入任务名称')
          return
        }
        this.list.unshift({
          id: +new Date(),
          name: this.todoName
        })
        this.todoName = ''
      }
    }
  })

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

7.【JS】禁止事件冒泡 与 默认事件

// 禁止事件冒泡

e.stopPropagation()

在Vue中是 @事件名.stop

// 禁止默认事件

e.preventDefault()

在Vue中是 @事件名.prevent

8.【JS】数组的两种种循环方式与reduce()实现累加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" >
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" ></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>

</head>
<body>
    <div class="container">
        <div class="giftList">
            <table>
                <thead>
                    <tr>
                        <th>名字</th>
                        <th>数量</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in list" :key="item.id">
                        <td>{{item.name}}</td>
                        <td>{{item.num}}</td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="2"><span>礼物总数:{{totalNum}} 个</span></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <script>
        const app = new Vue({
            el: '.giftList',
            data:{
                list: [
                {id: 1, name: '篮球', num: 1},
                {id: 2, name: '玩具', num: 2},
                {id: 3, name: '铅笔', num: 5}
                ]
            },
            computed:{
                totalNum(){
                    let sum = 0;
                    // this.list.forEach(function(item){
                    //     sum += item.num;
                    // })

                    // for(let i  = 0; i < this.list.length; i++){
                    //     sum += this.list[i].num;
                    // }

                    // reduce()方法,从左往右累加
                    // x为上一次调用reduce的结果值,y是本次调用的数组元素Item,末尾参数reduce( , 0),0表示x的初始值为0
                    sum = this.list.reduce(function(x, y){
                        return x + y.num;
                    },0);
                    return sum;
                }
            }
        })
    </script>
</body>
</html>

9.【JS】字符串截取slice()

  • str.slice(0,1) // 截取字符串首字符
  • str.slice(1) // 截取字符串从第二位字符开始

10.【JS】除法,保留小数

js保留小数的方法如下:(以保留两位为例)

1、toFixed()方法

需注意,保留两位小数,将数值类型的数据改变成了字符串类型

// 1. 四舍五入
var num = 1.7321;
num = num.toFixed(2);
console.log(num); //1.73
console.log(typeof num); //string


2、Math.floor(),不四舍五入 ,向下取整

Math.ceil() , 不四舍五入,向上取整

注意,不改变数据类型

// 2. 不四舍五入 向下取整
num = Math.floor(num * 100) / 100;
console.log(num);            //1.73
console.log(typeof num);     // number


3、字符串匹配

注意,先将数据转换为字符串,最后再转为数值类型

// 3. 不四舍五入 字符串匹配再转换
num = Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));
console.log(num);           //1.73
console.log(typeof num);    // number


4、四舍五入保留2位小数(若第二位小数为0,则保留一位小数)

注意,数据类型不变

//4.四舍五入保留2位小数(若第二位小数为0,则保留一位小数)  
        function keepTwoDecimal(num) {  
             var result = parseFloat(num);  
             if (isNaN(result)) {  
                 alert('传递参数错误,请检查!');  
                 return false;  
             }  
             result = Math.round(num * 100) / 100;  
             return result;  
        };
         keepTwoDecimal(num);
         console.log(num);            //1.73
         console.log(typeof num);     //number


5、四舍五入保留2位小数(不够位数,则用0替补)

注意,数据类型变为字符串类型

//5.四舍五入保留2位小数(不够位数,则用0替补)  
        function keepTwoDecimalFull(num) {  
             var result = parseFloat(num);  
             if (isNaN(result)) {  
                 alert('传递参数错误,请检查!');  
                 return false;  
             }  
             result = Math.round(num * 100) / 100;  
             var s_x = result.toString(); //将数字转换为字符串
             
             var pos_decimal = s_x.indexOf('.'); //小数点的索引值
             
 
             // 当整数时,pos_decimal=-1 自动补0  
             if (pos_decimal < 0) {  
                 pos_decimal = s_x.length;  
                 s_x += '.';  
             }
 
             // 当数字的长度< 小数点索引+2时,补0  
             while (s_x.length <= pos_decimal + 2) {  
                 s_x += '0';  
             }  
             return s_x;  
        }  
 
         console.log(keepTwoDecimalFull(120.5)); //120.50
         console.log(typeof keepTwoDecimalFull(120.5)); //string
         console.log(keepTwoDecimalFull(1.7321)); //1.73
         console.log(typeof keepTwoDecimalFull(1.7321)); //string

11.【JS】字符串转数字

1.使用parseInt()函数:该函数将字符串解析为整数。例如:

let str = "123";
let num = parseInt(str);
console.log(num); // 输出 123

2.使用parseFloat()函数:该函数将字符串解析为浮点数。例如:

let str = "3.14";
let num = parseFloat(str);
console.log(num); // 输出 3.14

3.使用Number()函数:该函数将字符串转换为数字。它可以处理整数和浮点数。例如:

let str = "42";
let num = Number(str);
console.log(num); // 输出 42
 
str = "3.14";
num = Number(str);
console.log(num); // 输出 3.14

4.使用加法操作符 (+):该操作符在字符串与数字相加时会自动将字符串转换为数字。例如:

let str = "42";
let num = +str;
console.log(num); // 输出 42

5.使用乘法操作符 (*):与加法操作符类似,乘法操作符也会将字符串转换为数字。例如:

let str = "3.14";
let num = str * 1;
console.log(num); // 输出 3.14

12.【Bootstrap】文字水平居中

class="text-center"

13.【JS】类型

14.【Vue2.x】v-bind:disabled禁用属性

Vue2.x的v-bind绑定控制<button>的disabled属性,满足条件则不能使用button

防止按钮(-)减到负数

15.【JS】Array.every()挨个检测数组的每一个元素

 16.【JS】数据类型与JSON互相转换

  • 其他数据类型 通过 JSON.stringify(需要转换的数据) 转换成 JSON格式
  • JSON数据 通过 JSON.parse(需要转换的数据) 转换成 其他数据类型

<!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" />
    <link rel="stylesheet" href="./css/inputnumber.css" />
    <link rel="stylesheet" href="./css/index.css" />
    
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>购物车</title>
  </head>
  <body>
    <div class="app-container" id="app">
      <!-- 顶部banner -->
      <div class="banner-box"><img src="./img/fruit.jpg" alt="" /></div>
      <!-- 面包屑 -->
      <div class="breadcrumb">
        <span>🏠</span>
        /
        <span>购物车</span>
      </div>
      <!-- 购物车主体 -->
      <div class="main">
        <div class="table">
          <!-- 头部 -->
          <div class="thead">
            <div class="tr">
              <div class="th">选中</div>
              <div class="th th-pic">图片</div>
              <div class="th">单价</div>
              <div class="th num-th">个数</div>
              <div class="th">小计</div>
              <div class="th">操作</div>
            </div>
          </div>
          <!-- 身体 -->
          <div class="tbody">
            <div class="tr" v-for="(item, index) in fruitList" :key="item.id" :class="{ active: item.isChecked }">
              <div class="td"><input type="checkbox" v-model="item.isChecked" /></div>
              <div class="td"><img :src="item.icon" alt="商品图片加载失败了喔" /></div>
              <div class="td">{{item.price}}</div>
              <div class="td">
                <div class="my-input-number">
                  <button :disabled="item.num <= 1" class="decrease" @click="subtract(item.id)"> - </button>
                  <span class="my-input__inner">{{item.num}}</span>
                  <button class="increase" @click="addOne(item.id)"> + </button>
                </div>
              </div>
              <div class="td">{{ item.num * item.price}}</div>
              <div class="td"><button @click="delOne(item.id)">删除</button></div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <div class="bottom">
          <!-- 全选 -->
          <label class="check-all">
            <input type="checkbox" v-model="isAll"/>
            全选
          </label>
          <div class="right-box">
            <!-- 所有商品总价 -->
            <span class="price-box">总价&nbsp;&nbsp;:&nbsp;&nbsp;¥&nbsp;<span class="price">{{totalPrice}}</span></span>
            <!-- 结算按钮 -->
            <button class="pay">结算( {{totalCount}} )</button>
          </div>
        </div>
      </div>
      <!-- 空车 -->
      <div v-show="fruitList.length === 0" class="empty">🛒空空如也</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <script>
      const defaultList = [
            {
              id: 1,
              icon: './img/火龙果.png',
              isChecked: true,
              num: 2,
              price: 6,
            },
            {
              id: 2,
              icon: './img/荔枝.png',
              isChecked: false,
              num: 7,
              price: 20,
            },
            {
              id: 3,
              icon: './img/榴莲.png',
              isChecked: false,
              num: 3,
              price: 40,
            },
            {
              id: 4,
              icon: './img/鸭梨.png',
              isChecked: true,
              num: 10,
              price: 3,
            },
            {
              id: 5,
              icon: './img/樱桃.png',
              isChecked: false,
              num: 20,
              price: 34,
            },
      ];
      const app = new Vue({
        el: '#app',
        data: {
          fruitList: JSON.parse(localStorage.getItem('fruit-list')) || defaultList,//一般给的初始值是[]空数组
        },
        methods:{
          // 删除一条
          delOne(id){
            this.fruitList = this.fruitList.filter(function(item){
              return item.id !== id;
            });
          },
          //个数增加1
          addOne(id){
            this.fruitList[id-1].num++;
          },
          //个数减少1
          subtract(id){
            this.fruitList[id-1].num--;
          }
        },
        computed:{
          // 默认计算属性:只能获取不能设置,要设置需要写完整写法
          // isAll () {
          //   // 必须所有的小选框都选中,全选按钮才选中 → every
          //   return this.fruitList.every(item => item.isChecked)
          // }
          
          // 完整写法 = get + set
          isAll: {
            get () {
              //使用Array.every()方法 检测所有小单选按钮是否都选中了,有一个没选中则返回false,全选不选中
              return this.fruitList.every(function(item){
                if(item.isChecked){
                  return true;
                };
                // 简写:item => item.isChecked;
              })
            },
            set (value) {
              // 基于拿到的布尔值,要让所有的小选框 同步状态
              this.fruitList.forEach(item => item.isChecked = value)
            }
          },
          // 计算选中数量
          totalCount(){
            return this.fruitList.reduce(function (x, y) {
              // 选中则累加
              if (y.isChecked === true){
                return x + y.num;
                // 否则返回上一次调用reduce的结果值
              }else{
                return x;
              }
            },0);
          },
          // 计算选中总价
          totalPrice(){
            return this.fruitList.reduce(function (x, y) {
              // 选中则累加
              if (y.isChecked === true){
                return x + y.price * y.num;
                // 否则返回上一次调用reduce的结果值
              }else{
                return x;
              }
            },0);
          }
        },
        watch:{
          // 对每次数据的改动做本地持久化,使用watch检测
          fruitList:{
            deep: true,
            handler(newValue,oldValue){
              // 需要将newValue存入本地,newValue是个复杂类型,转JSON格式存本地
              localStorage.setItem('fruit-list', JSON.stringify(newValue));
              // console.log(typeof newValue);// 类型:object
              // console.log(typeof localStorage.getItem('fruit-list'));// String JSON
              // console.log(typeof JSON.parse(localStorage.getItem('fruit-list')));// Object
              // console.log(typeof JSON.stringify(newValue));// String JSON 
            }
          }
        }
      })
    </script>
  </body>
</html>

 17.【JS】本地持久化

教程:JavaScript 存储对象 | 菜鸟教程 (runoob.com)

存入浏览器的缓存,记得转换JSON格式

浏览器查看

取出来使用,记得从JSON格式转回来

18.【JS |HTML】获取焦点

HTML的<input>的属性

19.【axios】ajax终极解决方案写法

/**
 * 目标:掌握async和await语法,解决回调函数地狱
 * 概念:在async函数内,使用await关键字,获取Promise对象"成功状态"结果值
 * 注意:await必须用在async修饰的函数内(await会阻止"异步函数内"代码继续执行,原地等待结果)
*/
// 1. 定义async修饰函数
async function getData() {
  // 2. await等待Promise对象成功的结果
  const pObj = await axios({url: 'http://hmajax.itheima.net/api/province'})
  const pname = pObj.data.list[0]
  const cObj = await axios({url: 'http://hmajax.itheima.net/api/city', params: { pname }})
  const cname = cObj.data.list[0]
  const aObj = await axios({url: 'http://hmajax.itheima.net/api/area', params: { pname, cname }})
  const areaName = aObj.data.list[0]


  document.querySelector('.province').innerHTML = pname
  document.querySelector('.city').innerHTML = cname
  document.querySelector('.area').innerHTML = areaName
}

getData()

还需到一种这样的写法,注意请求方式与大括号

20.【JS】${}模板字符串

21.【JS】展开运算符

22.【Vue2.x】e.target事件属性

在vue事件中传入$event,使用e.target和e.currentTarget有什么区别_event.target-CSDN博客

  • 22
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值