阅读视图

发现新文章,点击刷新页面。

【JS进阶】模拟正确处理并渲染后台数据

一、案例展示

js进阶第二天.png

二、部分数据展示

     const goodsList = [
            {
                id: '4001172',
                name: '称心如意手摇咖啡磨豆机咖啡豆研磨机',
                price: 289.9,
                picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',
                count: 2,
                spec: { color: '白色' }
            },
            {
                id: '4001009',
                name: '竹制干泡茶盘正方形沥水茶台品茶盘',
                price: 109.8,
                picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',
                count: 3,
                spec: { size: '40cm*40cm', color: '黑色' }
            },
     ]
  • ① 处为spec属性,是一个对象,在渲染时需要转换成字符串的形式
  • ② ④处为price和.amount模块中数据,需要保留两位小数
  • ③ 处为gift属性,渲染时要先判断是否有该属性,初始是字符串类型

三、前置知识点

1.数组转换为字符串方法:join();字符串转换为数组的方法:split()
2.累加器,用于数组求和的方法:reduce()
3.对象解构
4.模板字符串的使用

四、练习素材提供

<!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>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .list {
            width: 990px;
            margin: 100px auto 0;
        }

        .item {
            padding: 15px;
            transition: all .5s;
            display: flex;
            border-top: 1px solid #e4e4e4;
        }

        .item:nth-child(4n) {
            margin-left: 0;
        }

        .item:hover {
            cursor: pointer;
            background-color: #f5f5f5;
        }

        .item img {
            width: 80px;
            height: 80px;
            margin-right: 10px;
        }

        .item .name {
            font-size: 18px;
            margin-right: 10px;
            color: #333;
            flex: 2;
        }

        .item .name .tag {
            display: block;
            padding: 2px;
            font-size: 12px;
            color: #999;
        }

        .item .price,
        .item .sub-total {
            font-size: 18px;
            color: firebrick;
            flex: 1;
        }

        .item .price::before,
        .item .sub-total::before,
        .amount::before {
            content: "¥";
            font-size: 12px;
        }

        .item .spec {
            flex: 2;
            color: #888;
            font-size: 14px;
        }

        .item .count {
            flex: 1;
            color: #aaa;
        }

        .total {
            width: 990px;
            margin: 0 auto;
            display: flex;
            justify-content: flex-end;
            border-top: 1px solid #e4e4e4;
            padding: 20px;
        }

        .total .amount {
            font-size: 18px;
            color: firebrick;
            font-weight: bold;
            margin-right: 50px;
        }
    </style>
</head>

<body>
    <div class="list">
        <!-- <div class="item">
      <img src="https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg" alt="">
      <p class="name">称心如意手摇咖啡磨豆机咖啡豆研磨机 <span class="tag">【赠品】10优惠券</span></p>
      <p class="spec">白色/10寸</p>
      <p class="price">289.90</p>
      <p class="count">x2</p>
      <p class="sub-total">579.80</p>
    </div> -->
    </div>
    <div class="total">
        <div>合计:<span class="amount"></span></div>
    </div>
    <script>
        const goodsList = [
            {
                id: '4001172',
                name: '称心如意手摇咖啡磨豆机咖啡豆研磨机',
                price: 289.9,
                picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',
                count: 2,
                spec: { color: '白色' }
            },
            {
                id: '4001009',
                name: '竹制干泡茶盘正方形沥水茶台品茶盘',
                price: 109.8,
                picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',
                count: 3,
                spec: { size: '40cm*40cm', color: '黑色' }
            },
            {
                id: '4001874',
                name: '古法温酒汝瓷酒具套装白酒杯莲花温酒器',
                price: 488,
                picture: 'https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png',
                count: 1,
                spec: { color: '青色', sum: '一大四小' }
            },
            {
                id: '4001649',
                name: '大师监制龙泉青瓷茶叶罐',
                price: 139,
                picture: 'https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png',
                count: 1,
                spec: { size: '小号', color: '紫色' },
                gift: '50g茶叶,清洗球'
            }
        ]
        
    </script>
</body>

</html>

五、渲染实现

1.封装一个渲染函数

    function render(arr){
    }
    render(goodsList) //调用这个函数

2.map函数遍历数组,动态渲染div数量 (这是写在封装函数里的,单拿出来为了逻辑更清晰)

     document.querySelector(".list").innerHTML =arr.map(item => {
                  return `<div class="item">
                                 <img src="https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg" alt="">
                                  <p class="name">称心如意手摇咖啡磨豆机咖啡豆研磨机 <span class="tag">【赠品】10优惠券</span></p>
                                  <p class="spec">白色/10寸</p>
                                  <p class="price">289.90</p>
                                  <p class="count">x2</p>
                                  <p class="sub-total">579.80</p>
                          </div>`
    } ).join("")
    //由于map返回的是数组,要转换成字符串,然后添加到.list的div里面去
    //此时数据是写死的

3.对象解析后,添加到模板字符串中

    const { picture, name, price, count, spec, gift } = item
     return `
                    <div class="item">
                        <img src=${picture} alt="">
                        <p class="name">${name}<span class="tag">【赠品】10优惠券</span></p>
                        <p class="spec">白色/10寸</p>
                        <p class="price">${price.toFixed(2)}</p>
                        <p class="count">x${count}</p>
                        <p class="sub-total">${(price * 10 * count / 10).toFixed(2)}</p>
                    </div>
                `

4.处理spec对象

     const text = Object.values(spec).join("/")
     <p class="spec">${text}</p>
  • 首先用Object.values获取到spec中的数据,此时数据是数组的形式存在
  • 然后用join()拼接成字符串,用变量text接受
  • 最后填写到模板字符串中即可

5.赠品部分数据处理

    const str = gift ? gift.split(",").map(item => `<span class="tag">【赠品】${item}</span>`).join("") : ""
    <p class="name">${name} ${str}</p>
  • 首先要用三元运算符判断gift属性是否存在,不存在则为空
  • 然后gift是字符串类型,利用split()转换成数组然后map()遍历,原理等同于渲染函数render
  • 最后填写到模板字符串中

6.总计模块处理

    const total = goodsList.reduce((prev, item) => prev + (item.price * 100 * item.count) / 100, 0)
    document.querySelector(".amount").innerHTML = total.toFixed(2)
  • 利用ruduce()求和,千万不要忘记写初值
  • *100/100的做法是为了解决精度问题

六、JS部分完整代码

     function render(arr) {
            document.querySelector(".list").innerHTML = arr.map(item => {
                const { picture, name, price, count, spec, gift } = item
                const text = Object.values(spec).join("/") 
                const str = gift ? gift.split(",").map(item => `<span class="tag">【赠品】${item}</span>`).join("") : ""
                return `
                    <div class="item">
                        <img src=${picture} alt="">
                        <p class="name">${name} ${str}</p>
                        <p class="spec">${text}</p>
                        <p class="price">${price.toFixed(2)}</p>
                        <p class="count">x${count}</p>
                        <p class="sub-total">${(price * 10 * count / 10).toFixed(2)}</p>
                    </div>
                `
            }
            ).join("")
            
            const total = goodsList.reduce((prev, item) => prev + (item.price * 100 * item.count) / 100, 0)
            document.querySelector(".amount").innerHTML = total.toFixed(2)
        }
        render(goodsList)

【前端基础】原生JS实现Tab栏切换--根据价格筛选商品

一、效果展示

图片展示:

屏幕截图 2026-04-10 115729.png 效果展示视频:(忽略清朝画质)

4月10日.gif

二、前置知识点

1.解构赋值:数组解构、对象解构
2.事件委托,利用冒泡原理为多个元素绑定事件
3.forEach()--遍历数组,循环;filter()筛选数组
4.箭头函数

三、练习素材(html+css)

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第一天练习</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        li {
            list-style: none;
        }

        a {
            text-decoration: none;
        }

        .viewPort {
            width: 1024px;
            height: 780px;
            margin: 0 auto;
        }

        .list {
            margin-top: 30px;
            display: flex;
            width: 1024px;
            flex-wrap: wrap;
        }

        .item {
            width: 240px;
            margin-left: 10px;
            padding: 20px 30px;
            transition: all .5s;
            margin-bottom: 20px;
        }

        .item:nth-child(4n) {
            margin-left: 0;
        }

        .item:hover {
            box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
            transform: translate3d(0, -4px, 0);
            cursor: pointer;
        }

        .item img {
            width: 100%;
        }

        .item .name {
            font-size: 18px;
            margin-bottom: 10px;
            color: #666;
        }

        .item .price {
            font-size: 22px;
            color: firebrick;
        }

        .item .price::before {
            content: "¥";
            font-size: 14px;
        }

        .filter {
            display: flex;
            width: 990px;
            margin: 0 auto;
            padding: 50px 30px;
        }

        .filter a {
            padding: 10px 20px;
            background: #f5f5f5;
            color: #666;
            text-decoration: none;
            margin-right: 20px;
        }

        .filter a:active,
        .filter a:focus {
            background: #05943c;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="viewPort">
        <div class="filter">
            <a data-index="1" href="javascript:;">0-100元</a>
            <a data-index="2" href="javascript:;">100-300元</a>
            <a data-index="3" href="javascript:;">大于300元</a>
            <a href="javascript:;">全部区间</a>
        </div>
        <div class="list">
            <!-- <div class="item">
                <img src="" alt="">
                <p class="name"></p>
                <p class="price"></p>
            </div> -->
        </div>
    </div>
    <script>
        // 2. 初始化数据
        const goodsList = [
            {
                id: '4001172',
                name: '称心如意手摇咖啡磨豆机咖啡豆研磨机',
                price: '289.00',
                picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',
            },
            {
                id: '4001594',
                name: '日式黑陶功夫茶组双侧把茶具礼盒装',
                price: '288.00',
                picture: 'https://yanxuan-item.nosdn.127.net/3346b7b92f9563c7a7e24c7ead883f18.jpg',
            },
            {
                id: '4001009',
                name: '竹制干泡茶盘正方形沥水茶台品茶盘',
                price: '109.00',
                picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',
            },
            {
                id: '4001874',
                name: '古法温酒汝瓷酒具套装白酒杯莲花温酒器',
                price: '488.00',
                picture: 'https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png',
            },
            {
                id: '4001649',
                name: '大师监制龙泉青瓷茶叶罐',
                price: '139.00',
                picture: 'https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png',
            },
            {
                id: '3997185',
                name: '与众不同的口感汝瓷白酒杯套组1壶4杯',
                price: '108.00',
                picture: 'https://yanxuan-item.nosdn.127.net/8e21c794dfd3a4e8573273ddae50bce2.jpg',
            },
            {
                id: '3997403',
                name: '手工吹制更厚实白酒杯壶套装6壶6杯',
                price: '99.00',
                picture: 'https://yanxuan-item.nosdn.127.net/af2371a65f60bce152a61fc22745ff3f.jpg',
            },
            {
                id: '3998274',
                name: '德国百年工艺高端水晶玻璃红酒杯2支装',
                price: '139.00',
                picture: 'https://yanxuan-item.nosdn.127.net/8896b897b3ec6639bbd1134d66b9715c.jpg',
            },
        ]

四、功能JS模块

1.渲染函数的封装

function(arr){
    let str = "" //声明一个空字符串
    arr.forEach(item => {
        const {name,picture,price} = item //对象解构,快速批量的声明变量,缩减代码量
        str += `
            <div class="item">
                <img src=${picture} alt="">
                <p class="name">${name}</p>
                <p class="price">${price}</p>
            </div> 
        ` 
        //arr中有几个元素就渲染几个div,将数据填入 ${},动态渲染
    })
    document.queryselector(".list").innerHTML = str //将字符串放入.list的div盒子中
   }
   render(goodsList) //调用函数
    

2.绑定点击事件

    //事件委托,为父元素绑定点击事件
    document.queryselector("filter").addEventListener("click",e =>{
        const {tagName,dataset} = e.target //获取点击对象+对象解构
        let arr = goodsList //因为如果都不点击就显示全部元素,所以初始值将arr直接等于goodsList
        if(tagName === "A"){ //点击a标签时才触发,点击父元素空白区域不触发
            if (dataset.index === "1") {
                    arr = goodsList.filter(item => item.price > 0 && item.price <= 100)
                } else if (dataset.index === "2") {
                    arr = goodsList.filter(item => item.price >= 100 && item.price <= 300)
                } else if (dataset.index === "3") {
                    arr = goodsList.filter(item => item.price >= 300)
                }
                render(arr)
        }
    })

五、易错点

1.对象解构时,例如const {name,price} = item //这里是花括号,数组解构时是[]。并且对象解构时声名的变量名必须和数据中的属性名一致
2.函数不调用不执行,封装好函数后一定要调用执行
3.箭头函数省略原则:参数只有一个时,()可以省略;若函数中只有一句return语句时,{}和return都可以省略;!!!没有参数时,()一定不要省

❌