js、html实习 计数器 加减简 易购物车(js dom基础练习)

思路就是 循环生成 dom 利用 innerHtml赋值。

数量加减 需要传一个 唯一标识 这样才能 知道 点击的哪个,否则就是 一点击所有的都变了。 

<!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>计算</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .numBox {
            display: flex;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <div id="zjbox"></div>
</body>
<script>
    let arr = [{ id: 1, name: "苹果", num: 0,price:5,dzj:0 }, { id: 2, name: "李子", num: 0,price:6,dzj:0 }];
    htmlFn(arr);
    function add(data) {
        arr.map((item) => {
            if (item.id == data) {
                item.num++;
            }
        })
        htmlFn(arr);
    }
    function reduce(data) {
        arr.map((item) => {
            if (item.id == data) {
                if (item.num == 0) { //防止 数量 为负数
                    return
                }
                item.num--;
            }
        })
        htmlFn(arr);
    }
    function htmlFn(arr) {
        let box = document.getElementById("box");
        let zjbox=document.getElementById("zjbox");
        let boxHtml = "";
        let zj=0; //所有商品总价
        for (var i = 0; i < arr.length; i++) {

            let dzj=arr[i].num*arr[i].price; //单个商品总价
            zj+=dzj; 
            arr[i].dzj=dzj;
            boxHtml += `
           <div>
             <span>名称:${arr[i].name}</span>
             <span>单价:${arr[i].price}</span>
             <div class="numBox">
                数量:
                <button onclick='reduce(${arr[i].id})' >-</button>
                <input value=${arr[i].num} type="number" />
                <button onclick='add(${arr[i].id})'>+</button>
             </div>
             <span>单品总价:${dzj}</span>
            </div>
        `
        };
        box.innerHTML = boxHtml;
        zjbox.innerText=zj;
    }
    
</script>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_44058725/article/details/121223782
今日推荐