先倒入js,jquery,jstl所需要的配置,其中script操作如下
<script type="text/javascript">
//"+按钮出发的事件" ,传递进来这个按钮的id
function addNum(id){
//获取dom树,相邻的节点中的值(也就是要改变的数量)
var n = $('#'+id).next().html();
//强转为int类型后才能进行数学运算
var num = parseInt(n)+1;
//alert(num);
//更新点击按钮后的数量
$('#'+id).next().html(num);
//支付按钮,总金额的获取
var sum = $('input#input1').val();
//获取按钮事件所在循环的商品的价格,并计算新的总价
sum = parseFloat(sum) + parseFloat($('#span' + id).html());
//alert(parseInt($('#span' + id).html()));
//更新总价
$('input#input1').val(sum);
//其中$('#span' + id).html()中的获取商品单价的id运用了拼接的方法,实现了通过加
//减按钮的id来获取对应域的菜品的价格
}
function subNum(id){
var n = $('#'+id).prev().html();
//alert(id + "--" +JSON.stringify(n));
if(n==0){
alert("订单已清零");
}else{
var num = parseInt(n)-1;
// alert(num);
$('#'+id).prev().html(num);
var sum = $('input#input1').val();
//alert(parseInt($('#span1' + id).html()));
sum = parseFloat(sum) - parseFloat($('#span1' + id).html());
$('input#input1').val(sum);
}
}
</script>
html代码
<div style="height:350px;overflow:auto">
<%Map<String,Integer> car=(Map<String,Integer>)request.getSession().getAttribute("SESSION_CAR");
request.setAttribute("car",car); //必须要加这个
%>
<table border="2px" width="100%" bgcolor="#FFFFFF">
<tr>
<th>菜品样本</th>
<th>菜品名称与价格</th>
<th>数量</th>
</tr>
<c:set var="sum" value="0"></c:set>
<c:forEach items="${car}" var="s" varStatus="status">
<tr>
<c:set var="key" value="${s.key}" scope = "session"></c:set>
<%
FoodDao foodDao = new FoodDao();
Food food=foodDao.findFoodbyID((String)pageContext.findAttribute("key"));
request.setAttribute("food",food);
%>
<td width="150" height="100"><img alt="图片" src="${food.photo}" width="100" height="100" align="center"></td>
<td><span><c:out value="${food.foodname } "></c:out></span> <span id="span11button${status.index }"><c:out value=" ${food.value }"></c:out> </span>/份</td>
<td><button onclick="addNum(this.id)" id = "11button${status.index }">+</button><span><c:out value="${s.value}"></c:out></span><button onclick="subNum(this.id)" id = "1button${status.index }">-</button></td>
<c:set var="sum" value="${sum + (food.value * s.value) }"></c:set>
</tr>
</c:forEach>
</table>
</div>
<div>
<p style="color:red;font-size:18px;">应支付(元)</p>
<input id="input1" type="submit" style="width: 260px; height: 40px; margin-right:30px ;margin-top: 10px; background:grey ;" value="${sum }">
</div>
</div>