layui使用数据表格实现购物车功能

本文实例为大家分享了layui使用数据表格实现购物车功能的具体代码,供大家参考,具体内容如下

html部分

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>layui数据表格实现类购物车功能</title>
  <link rel="stylesheet" type="text/css" href="//layui.hcwl520.com.cn/layui/css/layui.css?v=201801090202" rel="external nofollow" />
  <script src="https://layui.hcwl520.com.cn/layui/layui.js?v=201801090202"></script>
  <link rel="stylesheet" href="css/index.css" rel="external nofollow" >
  <!--角标-->
  <link rel="shortcut icon" href="https://www.kaisir.cn/icon/favicon.ico" rel="external nofollow" >
  <script src="js/index.js"></script>
</head>
<body>

<div id="guide_panel">
  <blockquote class="layui-elem-quote">layui数据表格实现类购物车功能</blockquote>
  <ul class="layui-timeline">
    <li class="layui-timeline-item">
      <i class="layui-icon layui-timeline-axis"></i>
      <div class="layui-timeline-content layui-text">
        <h3 class="layui-timeline-title">使用方法</h3>
        <p>
          <br>1:单击左边商品列表任一商品,右边购物车数据表格会渲染一条数据,同时计算总数,合计金额。
          <br>2:购物车数据表格,数量/单价改变,金额改变,底部合计金额,数量,也会跟随改变
          <br>3:购物车数据表格,‘删除',删除当前所选商品
        </p>
      </div>
    </li>
  </ul>
</div>
  <div id="row_panel">
    <div class="table-panel">
      <table id="List1" lay-filter="List1"></table>
      <p>商品列表</p>
    </div>
    <div class="table-panel">
      <table id="List2" lay-filter="List2"></table>
      <p>购物车</p>
    </div>
    <div class="bottom-panel">
      <span>总数:</span><span style="color: red;margin-right: 15px" id="RechargeCount_TotalQty">---</span>
      <span>合计金额:</span><span style="color:red;margin-right: 20px" id="RechargeCount_TotalMoney">---</span>
    </div>
  </div>
</body>
</html>

css部分

*{
  margin: 0;
  padding: 0;
}
#guide_panel{
  width: 98%;
  margin: 0 auto;
}
#row_panel{
  width: 98%;
  height: 720px;
  margin: 0 auto;
  /*border: solid 1px red;*/
}
#row_panel .table-panel{
  width: 50%;
  height: 500px;
  float: left;
  text-align: center;
}
#row_panel .table-panel p{
  color:#BBBBBB;
}
#row_panel .bottom-panel{
  width: 100%;
  height: 40px;
  background: #F0F0F0;
  float: left;
  margin-top: 20px;
  text-align: right;
}
#row_panel .bottom-panel span{
  line-height: 40px;
  font-size: 18px;
}

js部分

layui.use(['layer', 'form', 'element', 'jquery', 'table', 'laydate'], function () {
  var form = layui.form, element = layui.element, $ = layui.$, layer = layui.layer,
    table = layui.table, laydate = layui.laydate;
  /**
   * 数据表格:定义表头数据
   * @type {{}}
   */
  var lan = {};
  lan.cpbm = "产品编码";
  lan.cpjm = "产品简码";
  lan.cpmc = "产品名称";
  lan.ckjj = "参考进价";
  lan.lpbz = "礼品标志";
  lan.spbh = "商品编号";
  lan.spmc = "商品名称";
  lan.sl = "数量";
  lan.dj = "单价";
  lan.je = "金额";
  lan.cz = "操作";
  /**
   * 购物车数据
   * @type {Array}
   */
  var goodsData = [];
  /**
   * 商品数据
   * @type {string}
   */
  var GoodsDataStr = "[{\"GoodsID\":\"20190308131925\",\"GoodsName\":\"123456\",\"NameCode\":\"123456\",\"GoodsClass\":\"13659603513393152\",\"GoodsType\":1,\"Price\":20,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0.8,\"IsDiscount\":1,\"Remark\":null,\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190308131956,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"个\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14157977930075136\",\"LAY_TABLE_INDEX\":0},{\"GoodsID\":\"20190301183528\",\"GoodsName\":\"测试2\",\"NameCode\":\"CS2\",\"GoodsClass\":\"14148378555485184\",\"GoodsType\":1,\"Price\":60,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190301183538,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"次\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14148379235683328\",\"LAY_TABLE_INDEX\":1},{\"GoodsID\":\"20190301183516\",\"GoodsName\":\"测试1\",\"NameCode\":\"CS1\",\"GoodsClass\":\"14148378482019328\",\"GoodsType\":1,\"Price\":50,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190301183522,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"次\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14148378983274496\",\"LAY_TABLE_INDEX\":2},{\"GoodsID\":\"6914068013626\",\"GoodsName\":\"纸巾\",\"NameCode\":\"zj\",\"GoodsClass\":\"13819788947571712\",\"GoodsType\":1,\"Price\":5,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":1,\"PointType\":0.1,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":\"%3Cp%3Enull%3C/p%3E\",\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190217092044,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"盒\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14130846812542976\",\"LAY_TABLE_INDEX\":3},{\"GoodsID\":\"20190126103924660\",\"GoodsName\":\"测试呀1\",\"NameCode\":\"CSY1\",\"GoodsClass\":\"13659654677299200\",\"GoodsType\":1,\"Price\":20,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":\"/FileSys/MemPhoto/198/20190126103959902.jpg\",\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":\"\",\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190126103959,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"次\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14099782024565760\",\"LAY_TABLE_INDEX\":4},{\"GoodsID\":\"20190124202652\",\"GoodsName\":\"是是是\",\"NameCode\":\"SSS\",\"GoodsClass\":\"13659603389480960\",\"GoodsType\":1,\"Price\":11,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":1,\"Images\":null,\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190124202657,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"1\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14097527869279232\",\"LAY_TABLE_INDEX\":5},{\"GoodsID\":\"699\",\"GoodsName\":\"自助烤肉\",\"NameCode\":\"ZZKR\",\"GoodsClass\":\"13819785158099968\",\"GoodsType\":1,\"Price\":50,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":50,\"Images\":\"/FileSys/MemPhoto/198/20190114153729870.jpg\",\"IsPoint\":1,\"PointType\":800,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":0,\"ExchangePoint\":0,\"CreateTime\":20190114153730,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":null,\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14083087561366528\",\"LAY_TABLE_INDEX\":6},{\"GoodsID\":\"20190114153056\",\"GoodsName\":\"积分衣服\",\"NameCode\":\"JFYF\",\"GoodsClass\":\"13819785158099968\",\"GoodsType\":1,\"Price\":0,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":\"/FileSys/GoodsIMG/198/20190114154132974.png\",\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":\"%3Cp%3Enull%3C/p%3E\",\"IsDelete\":0,\"IsGift\":1,\"ExchangePoint\":500,\"CreateTime\":20190114153221,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"1\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14083082487470080\",\"LAY_TABLE_INDEX\":7},{\"GoodsID\":\"20190114152247\",\"GoodsName\":\"积分裤子\",\"NameCode\":\"JFKZ\",\"GoodsClass\":\"13819785158099968\",\"GoodsType\":1,\"Price\":0,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":1,\"PointType\":800,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":1,\"ExchangePoint\":0,\"CreateTime\":20190114152321,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"1\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14083073653020672\",\"LAY_TABLE_INDEX\":8},{\"GoodsID\":\"20190114151536\",\"GoodsName\":\"裤子\",\"NameCode\":\"KZ\",\"GoodsClass\":\"13819785158099968\",\"GoodsType\":1,\"Price\":0,\"PriceUnit\":0,\"PriceNum\":0,\"XPrice\":0,\"Images\":null,\"IsPoint\":0,\"PointType\":0,\"MinDiscount\":0,\"IsDiscount\":0,\"Remark\":null,\"IsDelete\":0,\"IsGift\":1,\"ExchangePoint\":500,\"CreateTime\":20190114151658,\"CompID\":198,\"ShopID\":\"237\",\"MasterID\":\"237\",\"MeasureUnit\":\"1\",\"Specials\":0,\"IsShelf\":0,\"FreightTemplateID\":null,\"Id\":\"14083067377571840\",\"LAY_TABLE_INDEX\":9}]";
  var GoodsData = JSON.parse(GoodsDataStr);
  /**
   * 页面加载时执行
   */
  $(function () {
    console.table(GoodsData);

    /**
     * List1数据表格渲染(商品列表)
     */
    var ListTable1 = table.render({
      data:GoodsData,
      elem: '#List1',
      cellMinWidth: 95,
      //height: 'full-190',
      height: '460',
      minheight:430,
      page: true,
      limit: 10,
      limits: [10, 20, 30, 40],
      done: function (res) {
        if (res.rows && res.rows.length == 1) {
          var data = res.rows[0];

          GoodsList_onDblClickRow(data);
        }
      },
      cols: [
        [
          { field: 'GoodsID', title: lan.cpbm, align: 'left' },
          { field: 'NameCode', title: lan.cpjm, align: 'left' },
          { field: 'GoodsName', title: lan.cpmc, align: 'left' },
          {
            field: 'XPrice', title: lan.ckjj, align: 'right', templet: function (d) {
              return "<span style='color:red'>¥" + d.XPrice + "</span>";
            }
          },
          {
            field: 'IsGift', title: lan.lpbz, align: 'center', templet: function (d) {
              var _fm = '<div class="padding_top4 padding_left5">';
              _fm += d.IsGift == 1 ? '<i class="layui-icon layui-icon-ok" title=' + lan.lp + '></i>' : '<i class="layui-icon layui-icon-close" title=' + lan.flp + '></i>';
              _fm += "</div>";
              return _fm;
            }
          }
        ]
      ]
    });

    /**
     * List2数据表格渲染(购物车)
     */
    var ListTable2 = table.render({
      data:goodsData,
      elem: '#List2',
      cellMinWidth: 95,
      //height: 'full-190',
      height: '460',
      minheight:430,
      page: true,
      limit: 10,
      limits: [10, 20, 30, 40],
      cols: [
        [
          { field: 'GoodsID', title: lan.spbh },
          { field: 'GoodsName', title: lan.spmc },
          { field: 'Qty', title: lan.sl, edit: 'text' },
          { field: 'Price', title: lan.dj, edit: 'text' },
          { field: 'Money', title: lan.je },
          {
            title: lan.cz, align: "center", fixed: 'right', templet: function (d) {
              var html = '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delet">删除</a> ';
              return html;
            }
          }
        ]
      ],
      done: function (res) {
        $("#List2").siblings().find("td").each(function () {
          if ($(this).attr("data-edit") == 'text') {
            var num = $(this).find("div").text();
            $(this).append('<input class="layui-input layui-table-edit" value="' + num + '">')
          }
        })
      }

    });

    /**
     * 监听商品列表'行'单击事件
     */
    table.on('row(List1)', function (obj) {
      var data = obj.data;
      var isNew = true;
      var vKey = data.GoodsID; //产品编码
      //遍历购物车,是否存在产品;存在,数量+1 计算金额
      for (var i = 0; i < goodsData.length; i++) {
        var tRow = goodsData[i];
        if (vKey == tRow.GoodsID) {
          tRow.Qty = parseInt(tRow.Qty) + 1;
          tRow.Money = accMul(tRow.Qty, tRow.Price,2);
          isNew = false;
          break;
        }
      }
      //判断当前数据是否为新增数据
      if (isNew) {
        var tmpRow = {};
        tmpRow.Id = data.Id;
        tmpRow.GoodsID = data.GoodsID;
        tmpRow.GoodsName = data.GoodsName;
        tmpRow.Price = data.XPrice;
        tmpRow.Qty = 1;
        tmpRow.Money =(data.XPrice).toFixed(2);
        tmpRow.SalesCode = "";
        goodsData.push(tmpRow);
      }
      //console.log(goodsData);

      /**
       * 开始刷新购物车
       */
      shoppingCartRefresh();
    });

    /**
     * 监听购物车行删除事件
     */
    table.on('tool(List2)', function (obj, index) {
      var data = obj.data;
      if (obj.event === 'delet') {
        for (var i = 0; i < goodsData.length; i++) {
          var gd = goodsData[i];
          if (data.GoodsID == gd.GoodsID) {
            goodsData.splice(i, 1);
          }
        }
        /**
         * 开始刷新购物车
         */
        shoppingCartRefresh();
      }
    });

    /**
     * 购物车行编辑事件
     */
    table.on('edit(List2)', function (obj) {
      var data = goodsData;
      for (var i = 0; i < data.length; i++) {
        if (obj.data.Id == data[i].Id) {
          if (isNaN(data[i].Qty) || data[i].Qty < 0) {
            data[i].Qty = 0;
          }
          if (isNaN(data[i].Price) || data[i].Price < 0) {
            data[i].Price = 0;
          }
          data[i].Qty = Number(data[i].Qty); //数量:声明数字类型
          data[i].Price = parseFloat(data[i].Price).toFixed(2); //金额:声明小数类型
          data[i].Money = accMul(data[i].Qty, data[i].Price,2); //计算总金额:保留2位小数
        }
      }
      /**
       * 开始刷新购物车
       */
      shoppingCartRefresh();
    });

    /**
     * 购物车刷新函数
     */
    function shoppingCartRefresh(){
      var TotalQty = 0;
      var TotalMoney = 0;
      //数据表格重载
      ListTable2.reload({ data: goodsData });
      //计算总数 合计金额
      for (var i = 0; i < goodsData.length; i++) {
        TotalQty = accAdd(TotalQty, goodsData[i].Qty);
        TotalMoney = (accAdd(TotalMoney, parseFloat(goodsData[i].Money))).toFixed(2);
      }
      // console.log("总数量:"+TotalQty);
      // console.log("总金额:"+TotalMoney);
      $("#RechargeCount_TotalQty").html(TotalQty);
      $("#RechargeCount_TotalMoney").html(TotalMoney);
    }

    /**
     * 小数加法
     * @param arg1
     * @param arg2
     * @returns {number}
     */
    function accAdd(arg1,arg2){
      var r1,r2,m;
      try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
      try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
      m=Math.pow(10,Math.max(r1,r2));
      return (arg1*m+arg2*m)/m;
    }
    /**
     * 小数乘法
     * @param arg1
     * @param arg2
     * @param fix
     * @returns {*}
     */
    function accMul(arg1,arg2,fix) {
      if(!parseInt(fix)==fix)
      {
        return;
      }
      var m=0,s1=arg1.toString(),s2=arg2.toString();
      try{m+=s1.split(".")[1].length}catch(e){}
      try{m+=s2.split(".")[1].length}catch(e){}
      if(m>fix){
        return (Math.round(Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m-fix))/Math.pow(10,fix));
      }else if(m<=fix){
        return (Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)).toFixed(fix);
      }else{
        return (arg1*arg2).toFixed(fix);
      }
    }

  });

});

功能核心知识:

通过一个全局数组来存储,点击商品后,拿到的商品信息,用数据来驱动购物车表格显示。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • vuejs手把手教你写一个完整的购物车实例代码

    由于我们公司是主营业务是海淘,所以每个项目都是类似淘宝天猫之类的商城,那么购物车就是一个重点开发功能模块.介于之前我都是用jq来写购物车的,这次就用vuejs来写一个购物车.下面我就从全选,数量控制器,运费,商品金额计算等方法来演示一下一个能用在实际场景的购物车是怎么做出来的以及记录一下这次用vuejs踩过的坑. 1.一层数据结构-全选 下面这段代码和vuejs官网里面checkbox绑定很像.不明白的可以直接上vuejs官网看看. <!DOCTYPE html> <html lang=

  • JavaScript编写一个简易购物车功能

    网上关于购物车实现的代码非常多,今天看了一些知识点,决定自己动手写写,于是写了一个简易购物车,接下来讲解一下具体的实现. 1.用html实现内容: 2.用css修饰外观: 3.用js(jq)设计动效. 第一步:首先是进行html页面的设计,我用一个大的div将所有商品包含,然后用不同的div将不同的商品进行封装,商品列表中我用了ul li实现,具体实现代码如下(代码中涉及到的商品都是网上随便copy的,不具有参考价值): <div id="goods"> <div c

  • 原生js模拟淘宝购物车项目实战

    本文实例讲述了原生js模拟淘宝购物车实现代码.分享给大家供大家参考.具体如下: 通过JavaScript实现类似与淘宝的购物车效果,包括商品的单选.全选.删除.修改数量.价格计算.数目计算.预览等功能的实现.实现的效果图: 相应的代码: shoppingCart.html <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>JavaScript实现购物车项

  • Javascript操纵Cookie实现购物车程序

    复制代码 代码如下: /***************************************************************************************************** Name 购物车 Version 1.1 Author Vanni(凡林) url:www.27sea.com QQ:303590170 CreateDate 2005-05-31 Description 此类是基于JavaScript和客户端Cookie,请保证客户端开

  • js购物车实现思路及代码(个人感觉不错)

    复制代码 代码如下: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServer

  • js实现简单的购物车有图有代码

    如图:  全选按钮的实现为: 复制代码 代码如下: <input type="checkbox" name="all" onclick="checkAll()" />全选<br /> <input type="checkbox" name="item" value="3000" />笔记本电脑:3000元<br /> <input t

  • Javascript实现购物车功能的详细代码

    我们肯定都很熟悉商品购物车这一功能,每当我们在某宝某东上购买商品的时候,看中了哪件商品,就会加入购物车中,最后结算.购物车这一功能,方便消费者对商品进行管理,可以添加商品,删除商品,选中购物车中的某一项或几项商品,最后商品总价也会随着消费者的操作随着变化. 现在,笔者对购物车进行了简单实现,能够实现真实购物车当中的大部分功能.在本示例当中,用到了javascript中BOM操作,DOM操作,表格操作,cookie,json等知识点,同时,采用三层架构方式对购物车进行设计,对javascript的

  • 基于Vuejs实现购物车功能

    本文实例为大家分享了Vuejs购物车实现代码,供大家参考,具体内容如下 html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我的vue购物车</title> <link rel="stylesheet" href="css/bootstrap.min.css&q

  • js实现仿购物车加减效果

    效果图:  代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } body{ overflow-y: auto; } ul{ margin-top: 20px; border-top: 1px solid #666; } h1{ widt

  • 简单的前端js+ajax 购物车框架(入门篇)

    今天在公司实在没有事做,突然就想到写下商城的购物车的前端框架,当然我这里只有购物车的增删改查,也许写的并不是那么完善,但最重要的是一个入门,也希望js达人给些建议,好让我更上一个台阶. HOHO~~~开始咯: Js: 复制代码 代码如下: //为了省事,就没写自己的js ajax了 用了jquery的,当然你也可以添加到jquery的扩展方法内,哈哈,我太懒了,所以就写这里了. var _$ = { AJAX: function (urlparm, d, beforecall, successc

随机推荐