1. 程式人生 > >JQuery實現購物車數量加減總價累加

JQuery實現購物車數量加減總價累加

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8" />
<title>jQuery實現購物車多物品數量的加減+總價計算</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script> 
<script> 
$(function(){ 
$(".add").click(function(){
		var t = $(this).parent().find('input[class*=text_box]');
		t.val(parseInt(t.val())+1);
		setTotal();
	})

	$(".min").click(function(){
		var t = $(this).parent().find("input[class*=text_box]");
		t.val(parseInt(t.val())-1);
		if(parseInt(t.val())<0){
			t.val(0);
		}
		setTotal()
	})
	
	function setTotal(){
		var sum = 0;
		$("#tab td").each(function(){
		
		var num = parseInt($(this).find("input[class*=text_box]").val());
		var price = parseFloat($(this).find("span[class*=price]").text());
		sum += num*price;
		})
		$("#total").html(sum.toFixed(2));
	}
	setTotal();

}) 
</script> 
</head> 
<body> 
<table id="tab"> 
<tr> 
<td> 
<span>單價:</span><span class="price">1.50</span> 
<input class="min" name="" type="button" value="-" /> 
<input class="text_box" name="" type="text" value="1" /> 
<input class="add" name="" type="button" value="+" /> 
</td> 
</tr> 
<tr> 
<td> 
<span>單價:</span><span class="price">3.95</span> 
<input class="min" name="" type="button" value="-" /> 
<input class="text_box" name="" type="text" value="1" /> 
<input class="add" name="" type="button" value="+" /> 
</td> 
</tr> 
</table> 

<p>總價:<label id="total"></label></p> 
</body> 
</html> 

再舉一個獲取tr下面第一個td的值:

<!DOCTYPE html>  
<html lang="zh-CN">  
<head>  
    <meta charset="utf-8" />  
<title></title>   
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>   
<script>   
$(function(){   
$(".add").click(function(){  
        var t = $(this).parent().parent().find('td:first');  
        console.info(t.text()); 
    })  
      
})   
</script>   
</head>   
<body>   
<table id="tab">   
<tr>
<th>ID</th>
<th>name</th>    
<th>操作</th>   
</tr>
<tr>
<td class="id">123</td>
<td>admin</td>
<td><a href="#" class="add">彈</a></td>
</tr>

<tr>
<td class="id">456</td>
<td>ceshi</td>
<td><a href="#" class="add">彈</a></td>
</tr>

</body>   
</html>