编程语言
首页 > 编程语言> > 用JavaScript实现简易购物车

用JavaScript实现简易购物车

作者:互联网

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <style>
        .inputs{
            width:50px;
            text-align: center;
        }
    </style>
</head>
<body>
<div>
    你已购买的商品:女士衣服
</div>
<div>
    单价:<span id="jiage">100.00</span>
</div>
<div>
    数量为:
    <input type="button" id="jian" value="-">
    <input type="text" value="1" id="txt" class="inputs">
    <input type="button" value="+" id="jia">
</div>
<div>
    总价为:
    <span id="total">100.00</span>
</div>
<script src="js/js.js"></script>
</body>
</html>

JS:

{
    //找标签
    let jia = document.getElementById("jia");
    let jian=document.getElementById("jian");
    let txt = document.getElementById("txt");
    let total = document.getElementById("total");
    //事件处理
    let addFun = function(event){
        // 取出当前的值
        let v = txt.value ;   // 获取当前值,字符串
        let res = Number(v) + 1;
        txt.value = res ;
        console.info( res );
    };
    let jianFun=function (event) {
        let w = txt.value ;   // 获取当前值,字符串
        let rest = Number(w) - 1;
        txt.value = rest ;
        console.info( rest );
    };
    let totalFun=function(event){
        let x=jiage.innerText;
        let dx=txt.value;
        let add=x*dx;
        total.innerText=add;
        console.log(add);
};
    //  添加事件监听
    jia.addEventListener("click", addFun );
    jian.addEventListener("click", jianFun );
    jia.addEventListener("click", totalFun);
    jian.addEventListener("click", totalFun );
}

实现效果:
在这里插入图片描述

标签:jian,jia,JavaScript,value,购物车,简易,let,txt,click
来源: https://blog.csdn.net/weixin_46430385/article/details/105309361