简易的购物车功能实现 --- 19/03/20

这篇博客介绍了如何利用JQuery2.0版本实现一个简单的购物车功能。文中提到了实现界面,并列举了实现过程中涉及的关键知识点,包括button在form表单中的type属性设置、表单验证、阻止表单默认提交、attr与prop的区别以及数字小数点后的位数控制(toFixed(2))。
摘要由CSDN通过智能技术生成

本次使用的JS包为JQuery2.0版本

简单的实现界面:
购物车
以下为实现代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            width: 50%;
            margin: auto;
            padding-top: 50px;
        }
        input[type=number]{
            width: 30px;
        }
        table{
            text-align: center;
        }
        p{
            text-align: right;
            color: red;
            font-size: 30px;
        }
    </style>
    <script src="js/jquery2.0.js"></script>
</head>
<body>
    <form>
        商品名称:<input type="text" placeholder="请输入商品名称" id="goodsName" required>
        &nbsp;数量:<button type="button" class="decrease">-</button><input type="number" id="goodsNum" min="1" value="1" required><button type="button" class="add">+</button>
        &nbsp;单价:<input type="text" id="goodsPrice" required pattern="^-?([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$"><p></p>
        <button type="submit" id="submit">加入购物车</button>&nbsp;<button type="reset">重新输入</button>
    </form>
    <hr>
    <table width="100%" border="1" cellpadding="10" cellspacing="0">
        <thead>
        <tr>
           <th><input type="checkbox" id="checkAll"></th>
           <th>序号</th>
           <th>商品名称</th>
           <th>单价(¥)</th>
           <th>数量</th>
           <th>小计(¥)</th>
           <th>操作</th>
        </tr>
        </thead>
        <tr>
            <td><input type="checkbox"></td>
            <td>1</td>
            <td>舒适鞋子</td>
            <td>500.00</td>
            <td><button type="button" class="decrease">-</button><input type="number" min="1" value="1" required><button type="button" class="add">+</button></td>
            <td>500.00</td>
            <td><button>X</button></td>
        </tr>
    </table>
    <p>结算(费用计:¥<span>0</span></p>
</body>
</html>
<script>
    $(function () {
        //减
        $(".decrease").click(function () {
            if($(this).next().val() <=1){
                return;
            }
            $(this).next().val($(this).next().val()-1);
        })
        //加
        $(".add").click(function () {
            $(this).prev().val(Number($(this).prev().val())+1);
        })
        //添加商品到购物车
        $("form").submit(function () {
            var name = $("#goodsName").val();
            var num = $("#goodsNum").val();
            var price = Number($("#goodsPrice").val());
            var id = Number($("tbody tr:last-of-type td:nth-of-type(2)").text())+1;
            var node = '<tr>\n' +
                '            <td><input type="checkbox"></td>\n' +
                '            <td>'+id+'</td>\n' +
                '            <td>'+name+'</td>\n' +
                '            <td>'+price.toFixed(2)+'</td>\n' +
                '            <td><button type="button" class="decrease">-</button><input type="number" min="1" value="1" required><button type="button" class="add">+</button></td>\n' +
                '            <td>'+(num*price).toFixed(2)+'</td>\n' +
                '            <td><button>X</button></td>\n' +
                '        </tr>'
            $("table").append(node);
            return false;
        })
        //删除
        $("table").on('click','td:last-of-type button',function () {
            $(this).parents('tr').remove();
            countPrice();
        })
        //全选与全不选
        $("#checkAll").click(function () {
            $("input[type=checkbox]").prop("checked",$(this).prop('checked'));
            countPrice();
        })
        //单个复选框点击
        $("tbody").on('click','input[type=checkbox]',function () {
            $("#checkAll").prop('checked',$("tbody input[type=checkbox]").size() === $("tbody input[type=checkbox]:checked").size());
            countPrice();
        })
        //结算费用
        function countPrice() {
            var sum = 0;
            $("tbody input[type=checkbox]:checked").each(function () {
                sum += Number($(this).parents('tr').children('td:nth-last-of-type(2)').text());
            })
            $("p span").text(sum.toFixed(2));
        }
    })
</script>

运用到的知识点:

 1. 事件委托
 2. 节点添加
 3. 节点删除
 4. 节点获取(进阶选择器)
 5. H5表单新属性的运用  pattern   required的应用场景
 6. 全选全不选
 7. 底下的复选框控制全选全不选

需要注意的地方:

①:button在form表单中,具备提交功能,应该指明button的 type 属性
②:button只有在 submit 时才具备验证功能(required/pattern属性规则才能被验证出来)
③:阻止表单提交 return false
④:attr与prop的区别
⑤:toFixed(2) ‘2’ 表示保留两位小数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
网上购物网站的购物实现通常需要考虑以下几个方面: 1. 商品信息的存储:需要将每个商品的名称、价格、图片等信息存储到数据库中。 2. 购物的存储:需要将已选中的商品信息保存到用户的购物中,通常使用 cookie 或 session 存储购物信息。 3. 购物的展示:需要将购物中已选中的商品展示给用户,通常使用表格或列表的形式展示。 4. 购物的操作:需要实现添加商品、删除商品、修改商品数量等操作,通常使用 AJAX 技术实现无刷新操作。 下面是一个简单的购物实现示例: ```python from flask import Flask, render_template, request, make_response, redirect, url_for import json app = Flask(__name__) @app.route('/') def home(): # 查询商品信息,并展示给用户 products = [ { "name": "iPhone 12", "price": 6999, "image": "https://cdn.pixabay.com/photo/2021/08/19/07/41/iphone-12-6550774_960_720.jpg" }, { "name": "MacBook Pro", "price": 9999, "image": "https://cdn.pixabay.com/photo/2014/05/02/21/50/laptop-336378_960_720.jpg" }, { "name": "AirPods Pro", "price": 1299, "image": "https://cdn.pixabay.com/photo/2021/05/12/06/42/airpods-6240981_960_720.jpg" } ] return render_template('home.html', products=products) @app.route('/add', methods=['POST']) def add(): # 将商品添加到购物中 product = json.loads(request.data) cart = request.cookies.get('cart') if cart: cart = json.loads(cart) else: cart = {} if product['name'] in cart: cart[product['name']]['quantity'] += 1 else: cart[product['name']] = { 'quantity': 1, 'price': product['price'], 'image': product['image'] } resp = make_response(redirect(url_for('home'))) resp.set_cookie('cart', json.dumps(cart)) return resp @app.route('/cart') def cart(): # 展示购物中已选中的商品 cart = request.cookies.get('cart') if cart: cart = json.loads(cart) else: cart = {} return render_template('cart.html', cart=cart) @app.route('/remove', methods=['POST']) def remove(): # 从购物中删除商品 product = json.loads(request.data) cart = request.cookies.get('cart') if cart: cart = json.loads(cart) else: cart = {} if product['name'] in cart: del cart[product['name']] resp = make_response(redirect(url_for('cart'))) resp.set_cookie('cart', json.dumps(cart)) return resp ``` 这里我们使用 Flask 框架实现了一个简单的购物网站,其中包括了首页、添加商品到购物、查看购物、从购物中删除商品等功能。在添加商品和删除商品时,我们使用了 AJAX 请求实现无刷新操作。购物信息存储在用户的 cookie 中,使用 JSON 格式进行存储和读取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值