jquery 实现加入购物车功能

jquery 实现加入购物车功能,第1张

参考以下代码:

注意需要导入jquery.js.

<!DOCTYPE html>  

<html>  

  <head>  

    <title>购物车----jQuery</title>  

    <meta charset="utf-8" />  

    <style type="text/css">  

      h1 {  

        text-align:center  

      }  

      table {  

        margin:0 auto  

        width:60%  

        border:2px solid #aaa  

        border-collapse:collapse  

      }  

      table th, table td {  

        border:2px solid #aaa  

        padding:5px  

      }  

      th {  

        background-color:#eee  

      }  

    </style>  

    <script type="text/javascript" src="./js/jquery.js"></script>  

    <script type="text/javascript">  

      function add_shoppingcart(btn){//将btn(dom)转换为jQuery对象  

        //先获取商品名字和单价还有库存以备后面使用  

        var $tds = $(btn).parent().siblings()  

        //$tds.eq(0)是jQuery对象  $tds[0]是DOM对象  

        var name = $tds.eq(0).html()//string  

        var price = $tds.eq(1).html()//string  

        var stock = $tds.eq(3).html()//string  

          

        //查看库存是否还有<=0  

        if(stock <= 0){  

          return     

        }  

          

        //无论购物车中是否有该商品,库存都要-1  

        $tds.eq(3).html(--stock)  

          

        //在添加之前确定该商品在购物车中是否存在,若存在,则数量+1,若不存在则创建行  

        var $trs = $("#goods>tr")  

        for(var i=0i<$trs.lengthi++){  

          var $gtds = $trs.eq(i).children()  

          var gName = $gtds.eq(0).html()  

          if(name == gName){//若存在  

            var num = parseInt($gtds.eq(2).children().eq(1).val())  

            $gtds.eq(2).children().eq(1).val(++num)//数量+1  

            //金额从新计算  

            $gtds.eq(3).html(price*num)  

            return//后面代码不再执行  

          }  

        }  

        //若不存在,创建后追加  

        var li =  

          "<tr>"+  

            "<td>"+name+"</td>"+  

            "<td>"+price+"</td>"+  

            "<td align='center'>"+  

              "<input type='button' value='-' onclick='decrease(this)'/> "+  

              "<input type='text' size='3' readonly value='1'/> "+  

              "<input type='button' value='+' onclick='increase(this)'/>"+  

            "</td>"+  

            "<td>"+price+"</td>"+  

            "<td align='center'>"+  

              "<input type='button' value='x' onclick='del(this)'/>"+  

            "</td>"+  

          "</tr>"  

        //追加到#goods后面  

        $("#goods").append($(li))  

          

        //总计功能  

        total()  

      }  

        

      //辅助方法--单击购物车中的"+"  "-"  "x"按钮是找到相关商品所在td,以jQuery对象返回  

      function findStock(btn){  

        var name = $(btn).parent().siblings().eq(0).html()//获取商品名字  

        //注意table默认有行分组,若此处使用 $("#table1>tr:gt(0)")则找不到任何tr  

        var $trs = $("#table1>tbody>tr:gt(0)")  

        for(var i=0i<$trs.lengthi++){  

          var fName = $trs.eq(i).children().eq(0).html()  

          if(name == fName){//找到匹配的商品  

            return $trs.eq(i).children().eq(3)  

          }  

        }  

      }  

        

      //增加"+"功能  

      function increase(btn){  

        //获取该商品库存看是否<=0  

        var $stock = findStock(btn)  

        var stock = $stock.html()  

        if(stock <= 0){  

          return  

        }  

        //库存-1    

        $stock.html(--stock)  

        //购物车数据改变  

        var $td = $(btn).prev()  

        var num = parseInt($td.val())//number  

        //num此时为number类型(在计算时会自动转换为number类型)  

        $td.val(++num)  

        //获取单价,再加计算前要先转换为number类型  

        var price = parseInt($(btn).parent().prev().html())  

        $(btn).parent().next().html(num*price)  

          

        //总计功能  

        total()  

      }  

        

      //减少"-"功能  

      function decrease(btn){  

        //该商品数量=1时候不能再减少  

        var num = parseInt($(btn).next().val())  

        if(num <= 1){  

          return     

        }  

        var $stock = findStock(btn)  

        //库存+1  

        var stock = $stock.html()  

        $stock.html(++stock)  

        //商品数量-1  

        $(btn).next().val(--num)  

        //从新计算金额  

        var price = parseInt($(btn).parent().prev().html())  

        $(btn).parent().next().html(price*num)  

          

        //总计功能  

        total()  

      }  

        

      //"x"删除按钮功能  

      function del(btn){  

        //将商品数量归还库存  

        var $stock = findStock(btn)  

        var stock = parseInt($stock.html())  

        var num = parseInt($(btn).parent().prev().prev().children().eq(1).val())  

        $stock.html(num + stock)  

        //清空改行商品列表  

        $(btn).parent().parent().remove()  

          

        //总计功能  

        total()  

      }  

    //总计功能  

    function total(){  

      //获取所有购物车中的trs  

      var $trs = $("#goods tr")  

      var amount = 0  

      for(var i=0i<$trs.lengthi++){  

        var money = parseInt($trs.eq(i).children().eq(3).html())  

        amount += money  

      }  

      //写入总计栏  

      $("#total").html(amount)  

    }  

    </script>  

  </head>  

  <body>  

    <h1>真划算</h1>  

    <table id="table1">  

      <tr>  

        <th>商品</th>  

        <th>单价(元)</th>  

        <th>颜色</th>  

        <th>库存</th>  

        <th>好评率</th>  

        <th> *** 作</th>  

      </tr>     

      <tr>  

        <td>罗技M185鼠标</td>  

        <td>80</td>  

        <td>黑色</td>  

        <td>5</td>  

        <td>98%</td>  

        <td align="center">  

          <input type="button" value="加入购物车" onclick="add_shoppingcart(this)"/>  

        </td>  

      </tr>  

      <tr>  

        <td>微软X470键盘</td>  

        <td>150</td>  

        <td>黑色</td>  

        <td>9028</td>  

        <td>96%</td>  

        <td align="center">  

          <input type="button" value="加入购物车" onclick="add_shoppingcart(this)"/>  

        </td>  

      </tr>  

      <tr>  

        <td>洛克iphone6手机壳</td>  

        <td>60</td>  

        <td>透明</td>  

        <td>672</td>  

        <td>99%</td>  

        <td align="center">  

          <input type="button" value="加入购物车" onclick="add_shoppingcart(this)"/>  

        </td>  

      </tr>  

      <tr>  

        <td>蓝牙耳机</td>  

        <td>100</td>  

        <td>蓝色</td>  

        <td>8937</td>  

        <td>95%</td>  

        <td align="center">  

          <input type="button" value="加入购物车" onclick="add_shoppingcart(this)"/>  

        </td>  

      </tr>  

      <tr>  

        <td>金士顿U盘</td>  

        <td>70</td>  

        <td>红色</td>  

        <td>482</td>  

        <td>100%</td>  

        <td align="center">  

          <input type="button" value="加入购物车" onclick="add_shoppingcart(this)"/>  

        </td>  

      </tr>  

    </table>  

    

    <h1>购物车</h1>  

    <table>  

      <thead>  

        <tr>  

          <th>商品</th>  

          <th>单价(元)</th>  

          <th>数量</th>  

          <th>金额(元)</th>  

          <th>删除</th>  

        </tr>  

      </thead>  

      <tbody id="goods">  

      </tbody>  

      <tfoot>  

        <tr>  

          <td colspan="3" align="right">总计</td>  

          <td id="total"></td>  

          <td></td>  

        </tr>  

      </tfoot>  

    </table>      

  </body>  

</html>

最终效果图:

初步怀疑你的删除事件绑定有问题:新加入的DOM元素未绑定到事件。这种情况应该使用事件委派来做,你用 jQuery 吗?假设你的购物车列表的 HTML 结构如下:

<ul id="cartList">

    <li>

        购物车商品1

        <button>删除</button>

    </li>

    <li>

        购物车商品2

        <button>删除</button>

    </li>

    ……

</ul>

则删除购物车商品的代码为(用了 jQuery):

$('#cartList').on('click', 'button', function() {  // 委派 button 的点击事件

    $(this).parent().remove()  // 移除购物车里当前商品

})

页面jsp :

<%@ page language="java" contentType="text/html charset=utf-8"

    pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="

<%@ taglib uri="

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>易买网 - 首页</title>

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.1.1.js"></script>

<script type="text/javascript">

var contextPath = '${pageContext.request.contextPath }'

</script>

<script type="text/javascript" src="${pageContext.request.contextPath }/js/shopping.js"></script>

</head>

<body>

<jsp:include page="top.jsp" />

<div id="position" class="wrap">

您现在的位置:<a href="Home">易买网</a> &gt 购物车

</div>

<div class="wrap">

<div id="shopping">

<form action="" method="post">

<table>

<tr>

<th>商品名称</th>

<th>商品价格</th>

<th>购买数量</th>

<th> *** 作</th>

</tr>

<c:forEach items="${sessionScope.shopCar}"  var="item" varStatus="status">

<tr id="product_id_${item.proId}">

<td class="thumb"><img src="${item.proImg }" height="50" width="30" /><a href="Product?action=view&entityId=${item.proId}">${item.proName}</a></td>

<td class="price" id="price_id_1">

<span><fmt:formatNumber value="${item.proPrice}" type="NUMBER" minFractionDigits="2" /></span>

<input type="hidden" value="${item.proPrice}" />

</td>

<td class="number">

<dl>

<dt><span onclick="sub('number_id_${item.proId}','${item.proId}')">-</span><input id="number_id_${item.proId}" type="text" readonly="readonly" name="number" value="${item.proNum}" /><span onclick="addNum('number_id_${item.proId}','${item.proId}')">+</span></dt>

</dl>

</td>

<td class="delete"><a href="javascript:deleteItem('product_id_${item.proId}','${item.proId}')">删除</a></td>

</tr>

</c:forEach>

</table>

<div class="button"><input type="submit" value="" /></div>

</form>

</div>

</div>

<div id="footer">

Copyright &copy  kaka  292817678 itjob  远标培训. 

</div>

</body>

</html>

页面关联的js 自己去网上下载一个jquery

/*数量减少*/

function sub(id,proId){

//购买数量的值

var num = $('#'+id).val()

if(num > 1){

$('#'+id).val(num - 1)

}

edit(id,proId)

}

function edit(id,proId){

var url = contextPath + '/HomeCarManager'

//修改后的数量,购物明细的商品的id

num = $('#'+id).val()

$.post(url,{"num":num,"proId":proId},function (msg){

/*

if(msg == 'true'){

alert('修改成功')

} else {

alert('修改失败')

}*/

})

}

/**

 * 数量增加

 * @param {} id

 */

function addNum(id,proId){

//购买数量的值

var num = $('#'+id).val()

$('#'+id).val(parseInt(num) + 1)

edit(id,proId)

}

/**

 * 删除购物明细

 */

function deleteItem(trId,proId){

//

//console.log($("#"+trId))

//js删除页面节点

//$("#"+trId).remove()

var url = contextPath + '/HomeCarManager'

$.post(url,{"proId":proId},function (msg){

if(msg == 'true'){

//js删除页面节点

$("#"+trId).remove()

}

})

}

后台servlet1

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车处理类

 * @author @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCar extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//获取商品的id

String proId = req.getParameter("proId")

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

if(null != proId && !"".equals(proId)){

//返回添加购物车成功

//System.out.println("=============" + proId)

//根据商品的id查询商品

try {

Integer pId = Integer.parseInt(proId)

Product product = ps.findProductById(pId)

if(null != product){

//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车

Items it = new Items()

it.setProId(product.getProId())

it.setProName(product.getProName())

it.setProPrice(product.getProPrice())

it.setProImg(product.getProImg())

//先判断session范围是否有购物车

List<Items> shopCar = (List<Items>)req.getSession().getAttribute("shopCar")

if(null == shopCar){

//购物车

shopCar = new ArrayList<Items>()

}

//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量

if(shopCar.contains(it)){

int index  = shopCar.indexOf(it)//寻找购物车中包含购物明细在购物车中位置

Items items = shopCar.get(index)//获取购物车中存在的购物明细

items.setProNum(items.getProNum()+1)

} else {

shopCar.add(it)

}

//将购物车放入到session访问

req.getSession().setAttribute("shopCar", shopCar)

//返回

writer.print(true)

} else {

writer.print(false)

}

} catch (Exception e) {

e.printStackTrace()

writer.print(false)

}

} else {

writer.print(false)

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}

后台管理servlet 

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.mail.FetchProfile.Item

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车修改

 * @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCarManager extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

//获取参数

String proId = req.getParameter("proId")

String num = req.getParameter("num")

if(null != proId && null != num

&& !"".equals(proId) && !"".equals(num)){

try {

Integer pId = Integer.parseInt(proId)

Float pNum = Float.parseFloat(num)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

for(Items it : shopCar){

if(it.getProId()== pId){

it.setProNum(pNum)

}

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

} else {

//删除的 *** 作

try {

Integer pId = Integer.parseInt(proId)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

Items items = null

for(Items it : shopCar){

if(it.getProId()== pId){

items = it

break

}

}

if(null != items){

shopCar.remove(items)

req.getSession().setAttribute("shopCar",shopCar)

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11933581.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存