JS简单的商品添加功能

JS简单的商品添加功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        h1 {
            
            text-align: center;
        }

        table {
            margin: 0 auto;
            text-align: center;
            width: 800px;
        }

        .txt {
            width: 25px;
            text-align: center;
        }

        .reduce,
        .add {
            width: 20px;
        }

        .addBox {
            text-align: center;
            padding: 20px 10px;
        }

        .active {
            background-color: pink;
        }
    </style>
</head>
<body>
    <h1>商品的添加</h1>
    <div class="addBox">
        <label for="">商品名称:</label>
        <input type="text" placeholder="请输入商品的名称" class="productName">
        <label for="">商品单价:</label>
        <input type="text" placeholder="请输入商品的价格" class="productPrice">
        <button class="toAddCart">点击添加到购物车</button>
    </div>
    <table border='1' cellspacing='0' colspadding='0'>
        <thead>
            <tr>
                <th>商品</th>
                <th>价格</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id='tbody'>
        </tbody>
        <tfoot>
            <tr>
                <td><button class="clearCart">清空购物车</button></td>
                <td colspan="2" class="selectSum">选中商品数量</td>
                <td colspan="3"><span>总价:</span> <span class="totalPrice"></span></td>
            </tr>
        </tfoot>
    </table>
    <script src="./js/goods.js"></script>
</body>
</html>
let goodsList = [{
        id: 1,
        name: "荣耀70",
        price: 3999,
        num: 2
    },
    {
        id: 2,
        name: "Apple iPhone 13",
        price: 5999,
        num: 1
    },
    {
        id: 3,
        name: "小米11",
        price: 2980,
        num: 4
    },
    {
        id: 4,
        name: "HUAWEI P50",
        price: 3499,
        num: 2
    },
    {
        id: 5,
        name: "OPPO K9x",
        price: 2599,
        num: 1
    }
]
const tbody = document.querySelector('#tbody');
const addBox = document.querySelector('.addBox');
const productName = document.querySelector('.productName');
const productPrice = document.querySelector('.productPrice')

init();

function init() {
    render()
    addGoods()
    delGoods()
    calcCount()
    calcSum();

}
// 渲染数据
function render() {
    let str = '';
    for (let i = 0; i < goodsList.length; i++) {
        str += `
        <tr data-index='${goodsList[i].id}'>
            <td>${goodsList[i].name}</td>
            <td class="price">${goodsList[i].price}</td>
            <td>
                <button class="reduce" data-index='${goodsList[i].id}'>-</button>
                <input type="text" value='${goodsList[i].num}' class="txt">
                <button class="add" data-index='${goodsList[i].id}'>+</button>
            </td>
            <td class="count">${goodsList[i].price*goodsList[i].num}</td>
            <td><button class="del" >删除</button></td>
        </tr> `
    }
    tbody.innerHTML=str;
    
}
//添加商品
function addGoods(){
    addBox.addEventListener('click',clickAddHandler)
}
/* 添加商品事件 */
function clickAddHandler(e){
   if(e.target.className!=='toAddCart') return ;
   if(!(productName.value.length>0 && productPrice.value.length>0)) return
   const reg =/^\d{2,8}$/
   if(!(reg.test(+productPrice.value))) return
   const addObj={
        id: +new Date(),
        name: productName.value,
        price: productPrice.value,
        num: 1
   }
   goodsList.push(addObj)
   render()
   productName.value='';
   productPrice.value='';
}
// 删除商品
function delGoods(){
    tbody.addEventListener('click',clickDelGoodsHandler)
}
/* 实现删除功能 */
function clickDelGoodsHandler(e){
    if(!(e.target.className.includes('del'))) return;
    const res = window.confirm("确定删除吗?")
    if(!res) return;
    goodsList= goodsList.filter((item)=>e.target.parentNode.parentNode.dataset.index!=item.id)
    render();
}
//数量的计算
function calcCount(){
    tbody.addEventListener('click',clickCalcGoodsHandler)
}
/* 实现商品数量的加减,并进行小计 */
function clickCalcGoodsHandler(e){
    if(!((e.target.className.includes('add')) || (e.target.className.includes('reduce')))) return;
    let txt =document.querySelectorAll('#tbody .txt');
    let add =document.querySelectorAll('#tbody .add');
    let reduce =document.querySelectorAll('#tbody .reduce');
    let countPrice =document.querySelectorAll('#tbody .count')
    let index=goodsList.findIndex((item)=>e.target.parentNode.parentNode.dataset.index==item.id)
    if(e.target.className==='add'){
        /* 数量的+加 */
        let count =++txt[index].value
        add[index].previousElementSibling.innerHTML=count
        countPrice[index].innerHTML=count*goodsList[index].price;
    }else if(e.target.className==='reduce'){
        /* 数量的减少 */
        if(--txt[index].value <= 0) txt[index].value=1
        reduce[index].nextElementSibling.innerHTML=txt[index].value
        count=txt[index].value*goodsList[index].price;
        countPrice[index].innerHTML=count
    }
    /* 实现商品的总价功能 */ 
    calcSum();
}
// 实现商品的总价功能 +选中数量

function calcSum(){
    let countPrice =document.querySelectorAll('#tbody .count');
    let txt =document.querySelectorAll('#tbody .txt');
    const totalPrice = document.querySelector('tfoot .totalPrice');
    const selectSum = document.querySelector('tfoot .selectSum');
    let countSum=0,selectCount=0;
    for(let i=0;i<goodsList.length;i++){
         countSum +=  +countPrice[i].innerHTML;
         selectCount+= +txt[i].value;
    }
    totalPrice.innerHTML=countSum
    selectSum.innerHTML= '选中商品数量:' +selectCount
}

/* 清空所有的数据 */
clearData();


function clearData(){
    let clearCart = document.querySelector('tfoot .clearCart');
    clearCart.addEventListener('click',clickClearCartHandler)
}

function clickClearCartHandler(e){
    if(e.target.className !== 'clearCart') return;
    goodsList.length=0;
    render()
    calcSum()
}
txtChange()
function txtChange(){
    const txt =document.querySelectorAll('#tbody .txt');
    for(let i=0;i<goodsList.length;i++){
        txt[i].addEventListener('change',changeHandler)
    }
}
function changeHandler(e){
    if(e.target.className !=='txt') return;
    let count = e.target.parentNode.previousElementSibling.innerHTML;
    let countPrice =e.target.parentNode.nextElementSibling;
    countPrice.innerHTML  =count *  e.target.value
    calcSum()
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值