购物车效果点击+后增加 点击- 后减少

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <input id="jia" type="button" value="+">
    <span id="nr">0</span>
    <input id="jian" type="button" value="-">


    <script>
        let jia = document.getElementById('jia');
        let jian = document.getElementById('jian');
        let nr = document.getElementById('nr');
        // 方法一
        // jia.onclick = function () {
        //     nr.innerText++;
        // }
        // jian.onclick = function () {
        //     if (nr.innerText > 0) {
        //         nr.innerText--;
        //     }
        // }

        // 方法二
        jia.onclick = function () {
            nr.innerText++;
            jian.onclick = function () {

                if (nr.innerText == 0) {
                    jian.onclick = null;
                } else {
                    nr.innerText--;
                }
            }
        }
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/yehongrun/p/9125901.html