当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于JavaScript实现购物车功能

基于JavaScript实现购物车功能

2019年03月27日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了js实现购物车功能的具体代码,供大家参考,具体内容如下

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
  <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<div id="shop">
  <button id="btadd">我的购物车</button><br><br>

  <table id="cart">
    <thead>
    <tr>
      <th>单价</th>
      <th>数量</th>
      <th>小计</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
    <tfoot>
    <tr>
      <td colspan="4">购物车总金额:<span id="total">0.00</span></td>
    </tr>
    </tfoot>
  </table>
</div>
<div id="footer"></div>
<script>
  $('#read .page li a').click(function(){
    var n=$(this).html();

    $(this).parent().parent().next().children('p:nth-child('+n+')').slidedown(2000);
    $(this).parent().parent().next().children('p:nth-child('+n+')').siblings().css('display','none');
  })

  $('#btadd').click(function(){
    var p = randprice();
    var c = randcount();
    $('#cart tbody').append('<tr>'+
      '<td>'+p+'</td>'+
      '<td><input type="text" value="'+c+'"></td>'+
      '<td>'+parsefloat((p*c).tofixed(2))+'</td>'+
      '<td><a href="#" rel="external nofollow" >×</a></td>'+
      '</tr>');
    $('#total').html( gettotal() );
  });

  //为“删除”按钮(即x号)绑定事件监听函数,注意:x是后添加的,很多x执行的行为是一样的——使用事件代理
  $('#cart tbody').delegate('td > a', 'click',function(event){
    event.preventdefault();
    var a = event.target;
    $(a).parent().parent().remove();

  });
  //为“购买数量”输入框做事件绑定——使用事件代理
  $('#cart tbody').delegate('td > input','change', function(event){

    var input = event.target;
    var count = input.value;
    var price = $(input).parent().prev().html();
    $(input).parent().next().html( price*count );
    $('#total').html( gettotal() );
  })
  //计算购物车的总金额
  function gettotal(){
    var sum = 0;
    $('#cart tbody tr td:nth-child(3)').each(function(i, td){
      sum += parseint(td.innerhtml);
    })
    return sum;
  }


  function randprice(){
    var p = math.random()*100;
    p = p.tofixed(2);
    p = parsefloat(p);
    return p;
  }
  function randcount() {
    var c = math.floor(math.random() * 10 + 1);
    return c;

  }
  $('#header').load('php/header.php');
  $('#footer').load('php/footer.php');
  var theme=localstorage.getitem('chosetheme');
  applytheme(theme)

</script>

</body>
</html>

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网