JavaScript实现购物车

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <!-- <link rel="stylesheet" href="css.css"> -->
   <style type="text/css" media="screen">
       *{margin:0;padding:0;list-style-type:none;}
a{color:#666;text-decoration:none;}
table{border-collapse:collapse;border-spacing:0;border:0;}
body{color:#666;font:12px/180% Arial, Helvetica, sans-serif, "新宋体";}
clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden}
.clearfix{display:inline-table}
*html .clearfix{height:1%}
.clearfix{display:block}
*+html .clearfix{min-height:1%}
.fl{float:left;}
.fr{float:right;}
.catbox{width:940px;margin:100px auto;}
.catbox table{text-align:center;width:100%;}
.catbox table th,.catbox table td{border:1px solid #CADEFF;}
.catbox table th{background:#e2f2ff;border-top:3px solid #a7cbff;height:30px;}
.catbox table td{padding:10px;color:#444;}
.catbox table tbody tr:hover{background:RGB(238,246,255);}
.checkbox{width:60px;}
.check-all{ vertical-align:middle;}
.goods{width:300px;}
.goods span{width:180px;margin-top:20px;text-align:left;float:left;}
.goods img{width:100px;height:80px;margin-right:10px;float:left;}
.price{width:130px;}
.count{width:90px;}
.count .add, .count input, .count .reduce{float:left;margin-right:-1px;position:relative;z-index:0;}
.count .add, .count .reduce{height:23px;width:17px;border:1px solid #e5e5e5;background:#f0f0f0;text-align:center;line-height:23px;color:#444;}
.count .add:hover, .count .reduce:hover{color:#f50;z-index:3;border-color:#f60;cursor:pointer;}
.count input{width:50px;height:25px;line-height:15px;border:1px solid #aaa;color:#343434;text-align:center;padding:4px 0;background-color:#fff;z-index:2;}
.subtotal{width:150px;color:red;font-weight:bold;}
.operation span:hover,a:hover{cursor:pointer;color:red;text-decoration:underline;}
 
.foot{margin-top:0px;color:#666;height:48px;border:1px solid #c8c8c8;border-top:0;background-color:#eaeaea;background-image:linear-gradient(RGB(241,241,241),RGB(226,226,226));position:relative;z-index:8;}
.foot div, .foot a{line-height:48px;height:48px;}
.foot .select-all{width:80px;height:48px;line-height:48px;color:#666;text-align:center;}
.foot .delete{padding-left:10px;}
.foot .closing{border-left:1px solid #c8c8c8;width:103px;text-align:center;color:#666;font-weight:bold;cursor:pointer;background-image:linear-gradient(RGB(241,241,241),RGB(226,226,226));}
.foot .closing:hover{background-image:linear-gradient(RGB(226,226,226),RGB(241,241,241));color:#333;}
.foot .total{margin:0 20px;cursor:pointer;}
.foot  #priceTotal, .foot #selectedTotal{color:red;font-family:"Microsoft Yahei";font-weight:bold;}
.foot .selected{cursor:pointer;}
.foot .selected .arrow{position:relative;top:-3px;margin-left:3px;}
.foot .selected .down{position:relative;top:3px;display:none;}
.show .selected .down{display:inline;}
.show .selected .up{display:none;}
.foot .selected:hover .arrow{color:red;}
.foot .selected-view{width:938px;border:1px solid #c8c8c8;position:absolute;height:auto;background:#ffffff;z-index:9;bottom:48px;left:-1px;display:none;}
.show .selected-view{display:block;}
.foot .selected-view div{height:auto;}
.foot .selected-view .arrow{font-size:16px;line-height:100%;color:#c8c8c8;position:absolute;right:330px;bottom:-9px;}
.foot .selected-view .arrow span{color:#ffffff;position:absolute;left:0px;bottom:1px;}
 
#selectedViewList{padding:10px 20px 10px 20px;}
#selectedViewList div{display:inline-block;position:relative;width:100px;height:80px;border:1px solid #ccc;margin:10px;float:left;}
#selectedViewList div img{width:100px;height:80px;margin-right:10px;float:left;}
#selectedViewList div span{display:none;color:#ffffff;font-size:12px;position:absolute;top:0px;right:0px;width:60px;height:18px;line-height:18px;text-align:center;background:#000;cursor:pointer;}
#selectedViewList div:hover span{display:block;}
   </style>
</head>
<body>
    <div class="catbox">
    <!-- 使用table标签制作整个购物车的结构和样式 -->
    <table id="cartTable">
        <thead>
        <tr>
            <th><label>
                <input class="check-all check" type="checkbox">  全选</label></th>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>小计</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 为每一行商品信息设置类名为:on
 
            默认是使用check每种商品中的一个商品,即,默认选中4个不同类型的商品
        -->
        <tr class="on">
            <td class="checkbox"><input class="check-one check" type="checkbox"></td>
            <td class="goods"><img src="" alt=""><span>Casio/卡西欧 EX-TR350</span></td>
            <td class="price">5999.88</td>
            <td class="count"><span class="reduce"></span>
                <input class="count-input" type="text" value="1">
                <span class="add">+</span></td>
            <td class="subtotal">5999.88</td>
            <td class="operation"><span class="delete">删除</span></td>
        </tr>
        <tr class="on">
            <td class="checkbox"><input class="check-one check" type="checkbox"></td>
            <td class="goods"><img src="" alt=""><span>Canon/佳能 PowerShot SX50 HS</span></td>
            <td class="price">3888.50</td>
            <td class="count"><span class="reduce"></span>
                <input class="count-input" type="text" value="1">
                <span class="add">+</span></td>
            <td class="subtotal">3888.50</td>
            <td class="operation"><span class="delete">删除</span></td>
        </tr>
        <tr class="on">
            <td class="checkbox"><input class="check-one check" type="checkbox"></td>
            <td class="goods"><img src="" alt=""><span>Sony/索尼 DSC-WX300</span></td>
            <td class="price">1428.50</td>
            <td class="count"><span class="reduce"></span>
                <input class="count-input" type="text" value="1">
                <span class="add">+</span></td>
            <td class="subtotal">1428.50</td>
            <td class="operation"><span class="delete">删除</span></td>
        </tr>
        <tr class="on">
            <td class="checkbox"><input class="check-one check" type="checkbox"></td>
            <td class="goods"><img src="" alt=""><span>Fujifilm/富士 instax mini 25</span></td>
            <td class="price">640.60</td>
            <td class="count"><span class="reduce"></span>
                <input class="count-input" type="text" value="1">
                <span class="add">+</span></td>
            <td class="subtotal">640.60</td>
            <td class="operation"><span class="delete">删除</span></td>
        </tr>
        </tbody>
    </table>
    <!-- 制作购物车表格下面的结构样式 -->
    <div class="foot" id="foot">
        <label class="fl select-all"><input type="checkbox" class="check-all check">  全选</label>
        <a class="fl delete" id="deleteAll" href="javascript:;">删除</a>
        <div class="fr closing" onclick="getTotal();">结 算</div>
        <!-- 隐藏input标签   -->
        <input type="hidden" id="cartTotalPrice">
 
        <div class="fr total">合计:¥<span id="priceTotal">11957.48</span></div>
        <div class="fr selected" id="selected">已选商品<span id="selectedTotal">4</span>件<span class="arrow up">︽</span><span class="arrow down">︾</span></div>
         <div class="selected-view">
           <div id="selectedViewList" class="clearfix">
 
            <div><img src="http://www.jq22.com/demo/jquery-guc20151105/images/1.jpg"><span class="del" index="0">取消选择</span></div>
 
            <div><img src="http://www.jq22.com/demo/jquery-guc20151105/images/2.jpg"><span class="del" index="1">取消选择</span></div>
 
            <div><img src="http://www.jq22.com/demo/jquery-guc20151105/images/3.jpg"><span class="del" index="2">取消选择</span></div>
             
            <div><img src="http://www.jq22.com/demo/jquery-guc20151105/images/4.jpg"><span class="del" index="3">取消选择</span></div>
           </div>
            <span class="arrow">◆<span>◆</span></span>
         </div>
    </div>
</div>
  <script >
       /**
   * Created by an www.jq22.com
   */
  window.onload = function () {
      // 当家在整个js文件的时候,function getElementsByClassName() { [native code] }
      // 这个函数并没有执行
      if (!document.getElementsByClassName) {
          alert("执行了");
          // getElementsByClassName:获取所有指定的类名
          document.getElementsByClassName = function (cls) {
              console.log(cls);  //check    check-all
              var ret = [];
              var els = document.getElementsByTagName('*');
              console.log(els);  //长度是104
              for (var i = 0, len = els.length; i < len; i++) {
              // indexof()方法可返回某个指定的字符串中首次出现的位置
              // stringObject.indexOf(searchvalue,fromindex)
              // 说明:该方法将从头到尾地检索字符串 stringObject,
              // 看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex
              // 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,
              // 则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。
 
                  if (els[i].className.indexOf(cls + ' ') >=0 || els[i].className.indexOf(' ' + cls + ' ') >=0 || els[i].className.indexOf(' ' + cls) >=0) {
                      ret.push(els[i]);
                  }
              }
              console.log(ret);
              return ret;
          }
       
      }
// console.log(document.getElementsByClassName);
 
      var table = document.getElementById('cartTable'); // 购物车表格
      var selectInputs = document.getElementsByClassName('check'); // 所有勾选框
      var checkAllInputs = document.getElementsByClassName('check-all') // 全选框
      var tr = table.children[1].rows; //行
      var selectedTotal = document.getElementById('selectedTotal'); //已选商品数目容器
      var priceTotal = document.getElementById('priceTotal'); //总计
      var deleteAll = document.getElementById('deleteAll'); // 删除全部按钮
      var selectedViewList = document.getElementById('selectedViewList'); //浮层已选商品列表容器
      var selected = document.getElementById('selected'); //已选商品
      var foot = document.getElementById('foot');
 
      // 更新总数和总价格,已选浮层
      function getTotal() {
          var seleted = 0;
          var price = 0;
          var HTMLstr = '';
          for (var i = 0, len = tr.length; i < len; i++) {
              //通过for循环,遍历到某一行,则通过getElementsByTagName('input')[0].checked,
              // 这句话选中这个商品
              if (tr[i].getElementsByTagName('input')[0].checked) {
                  //为这个商品设置类名on
                  tr[i].className = 'on';
                  //拿到商品的数量之后,在原来已经选中的商品中继续叠加,叠加到商品总的数量上
                  seleted += parseInt(tr[i].getElementsByTagName('input')[1].value);
                   // 拿到选中商品的对应的价格,叠加到商品总额中
                  price += parseFloat(tr[i].cells[4].innerHTML);
                  // 把获取到的商品图片添加到浮层中
                  HTMLstr += '<div><img src="' + tr[i].getElementsByTagName('img')[0].src + '"><span class="del" index="' + i + '">取消选择</span></div>'
              }
              else {
                  // 如果没有选中该行商品,则将没有选中的类名置为空
                  tr[i].className = '';
              }
          }
          selectedTotal.innerHTML = seleted;
          // toFixed(num)可以把Number四舍五入为指定小数位数的数字
          // num规定小数的位数,是0~20之间的值,包括0和20,有些实现可以支持更大的数值范围
          // 如果省略了该参数,将用0代替。
          priceTotal.innerHTML = price.toFixed(2);
          selectedViewList.innerHTML = HTMLstr;
          // 如果没有选中任何商品,则还是默认的状态
          if (seleted == 0) {
              foot.className = 'foot';
          }
      }
      // 计算单行价格
      // 把每一行的标签tr当做参数
      function getSubtotal(tr) {
          console.log(tr);//打印出来的是对应的行标签tr里面所包含的所有的内容
          var cells = tr.cells;//把每一种商品中的所有属性赋值给cells
          var price = cells[2]; //单价 ,把每一种商品的第二个属性即,价格,赋值给price
          var subtotal = cells[4]; //小计td,解释同上
          // 选中商品数量对应的input标签,赋值给countInput
          var countInput = tr.getElementsByTagName('input')[1]; //数目input
          // console.log(tr.getElementsByTagName('input')[1]);
          var span = tr.getElementsByTagName('span')[1]; //-号
          //写入HTML
          subtotal.innerHTML = (parseInt(countInput.value) * parseFloat(price.innerHTML)).toFixed(2);
          //如果数目只有一个,把-号去掉
          if (countInput.value == 1) {
              span.innerHTML = '';
          }else{
              span.innerHTML = '-';
          }
      }
 
      // 点击选择框
      for(var i = 0; i < selectInputs.length; i++ ){
          selectInputs[i].onclick = function () {
              if (this.className.indexOf('check-all') >= 0) { //如果是全选,则吧所有的选择框选中
 
                  console.log(this.className.indexOf('check-all'));//打印的是0
                    //selectInputs.length=6
                  for (var j = 0; j < selectInputs.length; j++) {
                      //6
                      selectInputs[j].checked = this.checked;  //全部选中复选框
                      //这里的this是指所有的<input class=​"check-all check" type=​"checkbox">​
 
                  }
              }
              if (!this.checked) { //只要有一个未勾选,则取消全选框的选中状态
                  for (var i = 0; i < checkAllInputs.length; i++) {
                      checkAllInputs[i].checked = false;
                  }
              }
              //再次调用getTotal()函数,迭代更新
              getTotal();//选完更新总计
          }
      }
 
      // 显示已选商品弹层
      selected.onclick = function () {
          if (selectedTotal.innerHTML != 0) {
              foot.className = (foot.className == 'foot' ? 'foot show' : 'foot');
          }
      }
 
      //已选商品弹层中的取消选择按钮
      // 这里的e代表事件对象,即所谓的事件驱动源
      // 在这里这个e,即是指鼠标点击事件
      selectedViewList.onclick = function (e) {
          console.log(e);
          //为了实现多种浏览器的兼容
          var e = e || window.event;
          var el = e.srcElement;
          console.log(el);  //<img src="file:///C:/Users/Administrator/Desktop/2/style.html">
          if (el.className=='del') {
              var input =  tr[el.getAttribute('index')].getElementsByTagName('input')[0]
              console.log(input);  //<span class="del" index="3">取消选择</span>
              input.checked = false;
              // 这句话的意思是删除<span class="del" index="3">取消选择</span>
              // 所对应的div标签
               input.onclick(this);  //这里面的this是我自己添加到里面的,但是效果是一样的
          }
      }
 
      //为每行元素添加事件
      for (var i = 0; i < tr.length; i++) {
          //将点击事件绑定到tr元素
          tr[i].onclick = function (e) {
              var e = e || window.event;
              var el = e.target || e.srcElement; //通过事件对象的target属性获取触发元素
              var cls = el.className; //触发元素的class名
              console.log(cls);   //add /reduce
              //这里的this是指tr标签
              var countInout = this.getElementsByTagName('input')[1]; // 数目input
              var value = parseInt(countInout.value); //数目
              //通过判断触发元素的class确定用户点击了哪个元素
              switch (cls) {
                  case 'add': //点击了加号
                      countInout.value = value + 1;
                      getSubtotal(this);
                      break;
                  case 'reduce': //点击了减号
                      if (value > 1) {
                          countInout.value = value - 1;
                          getSubtotal(this);  //this指的是tr标签
                      }
                      break;
                  case 'delete': //点击了删除
                      var conf = confirm('确定删除此商品吗?');
                      if (conf) {
                          this.parentNode.removeChild(this);  //this指的是tr标签
                      }
                      break;
              }
              // 更新总数和总价格
              getTotal();
          }
          // 给数目输入框绑定keyup事件
          tr[i].getElementsByTagName('input')[1].onkeyup = function () {
              var val = parseInt(this.value);  //是数字,number类型的
              console.log(this.value); //<input class="count-input" type="text" value="1">
              //判断输入框内只能是大于零的整数,不能是除数字之外的其他非法字符
              if (isNaN(val) || val <= 0) {
                  val = 1;
              }
              // 下面这句话的意思是防止用户在手动输入商品数量的时候出现小数,即使出现小数
              // 也会取整的
              if (this.value != val) {
                  this.value = val;
              }
              getSubtotal(this.parentNode.parentNode); //更新小计
              console.log(this.parentNode.parentNode); //指的是tr标签
              getTotal(); //更新总数
          }
      }
      // 点击全部删除
      deleteAll.onclick = function () {
          if (selectedTotal.innerHTML != 0) {
              var con = confirm('确定删除所选商品吗?'); //弹出确认框
              if (con) {
                  for (var i = 0; i < tr.length; i++) {
                      // 如果被选中,就删除相应的行
                      if (tr[i].getElementsByTagName('input')[0].checked) {
                          tr[i].parentNode.removeChild(tr[i]); // 删除相应节点
                          i--; //回退下标位置
                      }
                  }
              }
          } else {
              alert('请选择商品!');
          }
          getTotal(); //更新总数
      }
      console.log("\u767e\u5ea6\u641c\u7d22\u3010\u7d20\u6750\u5bb6\u56ed\u3011\u4e0b\u8f7d\u66f4\u591aJS\u7279\u6548\u4ee3\u7801");
      // 默认全选
      checkAllInputs[0].checked = true;
      checkAllInputs[0].onclick(this);  //这里的this是指的是window
      console.log(this);
  }
  </script>
</body>
</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现购物车的基本流程如下: 1. 创建一个空的购物车数组,用于存放商品信息。 2. 在页面中展示商品列表,并为每个商品添加“加入购物车”按钮。 3. 点击“加入购物车”按钮时,获取当前商品的信息(如商品ID、名称、价格等),将其添加到购物车数组中。 4. 在页面中展示购物车列表,包括每个商品的信息以及数量、总价等信息。 5. 实现购物车中商品数量、总价的实时更新,例如增加或减少商品数量时,购物车列表应该实时更新。 6. 实现删除购物车中的商品,同时更新购物车列表和购物车数组。 7. 实现结算功能,包括计算购物车中所有商品的总价、应付款项等信息。 下面是一个简单的示例代码: HTML部分: ``` <!-- 商品列表 --> <div id="product-list"> <div class="product" data-id="1" data-name="商品1" data-price="10.00"> <h3>商品1</h3> <p>价格:10.00元</p> <button class="add-to-cart">加入购物车</button> </div> <div class="product" data-id="2" data-name="商品2" data-price="20.00"> <h3>商品2</h3> <p>价格:20.00元</p> <button class="add-to-cart">加入购物车</button> </div> ... </div> <!-- 购物车列表 --> <div id="cart-list"> <h2>购物车</h2> <table> <thead> <tr> <th>商品名称</th> <th>单价</th> <th>数量</th> <th>总价</th> <th>操作</th> </tr> </thead> <tbody> </tbody> </table> <div id="cart-summary"> <p>总价:<span id="total-price">0.00</span>元</p> <button id="checkout">结算</button> </div> </div> ``` JS部分: ``` // 购物车数组 var cart = []; // 获取商品列表和购物车列表元素 var productList = document.getElementById('product-list'); var cartList = document.getElementById('cart-list'); // 添加商品到购物车 function addToCart(id, name, price) { // 检查购物车中是否已存在该商品 for (var i = 0; i < cart.length; i++) { if (cart[i].id === id) { cart[i].quantity++; return; } } // 如果购物车中不存在该商品,则添加到购物车数组中 cart.push({ id: id, name: name, price: price, quantity: 1 }); } // 渲染购物车列表 function renderCart() { // 清空购物车列表 cartList.querySelector('tbody').innerHTML = ''; // 遍历购物车数组,生成购物车列表 for (var i = 0; i < cart.length; i++) { var item = cart[i]; var tr = document.createElement('tr'); tr.innerHTML = ` <td>${item.name}</td> <td>${item.price.toFixed(2)}</td> <td>${item.quantity}</td> <td>${(item.price * item.quantity).toFixed(2)}</td> <td><button class="remove-from-cart" data-id="${item.id}">删除</button></td> `; cartList.querySelector('tbody').appendChild(tr); } // 更新总价 var totalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0); document.getElementById('total-price').textContent = totalPrice.toFixed(2); } // 商品列表添加点击事件 productList.addEventListener('click', function(event) { var target = event.target; if (target.classList.contains('add-to-cart')) { var product = target.closest('.product'); var id = product.dataset.id; var name = product.dataset.name; var price = parseFloat(product.dataset.price); addToCart(id, name, price); renderCart(); } }); // 购物车列表添加点击事件 cartList.addEventListener('click', function(event) { var target = event.target; if (target.classList.contains('remove-from-cart')) { var id = target.dataset.id; cart = cart.filter(item => item.id !== id); renderCart(); } }); // 结算按钮添加点击事件 document.getElementById('checkout').addEventListener('click', function(event) { var totalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0); alert(`您需要支付${totalPrice.toFixed(2)}元`); }); ``` 以上代码仅为示例,实际项目中可能需要根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值