日期:2014-05-16  浏览次数:20462 次

求把这段代码写成类_在线求助

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script>
$(function(){
var xb_price = $("#price_s").html();
var t = $("#text_box");
var xb_number = $("#text_box").val();
$("#add").click(function(){  
t.val(parseInt(t.val())+1)
setTotal();
})
$("#min").click(function(){
t.val(parseInt(t.val())-1)
setTotal();
})
function setTotal(){
$("#total").html((parseInt(t.val())* xb_price).toFixed(2));
}
setTotal();
});
</script>
</head>
<body>
<div>
<p>单价:<span id="price_s">3.95</span></p>
<input id="min" name="" type="button" value="-" />
<input id="text_box" name="" type="text" value="10" />
<input id="add" name="" type="button" value="+" />
</div>

<p>总价:<label id="total"></label></p>
</body>
</html>



如果有多个div  希望都可以使用 能得出来总价。谢谢。

------解决方案--------------------

<script src="jquery-1.7.2.min.js"></script> 
<script>
$(function(){
$.fn.extend({
money:function(){
var _this = $(this);
$.fn.total(_this);
_this.each(function(i,item){
 $(item).find('.min').click(function(){
$.fn.down(_this,$(item));
 })
 $(item).find('.add').click(function(){
$.fn.up(_this,$(item));
 })
})
},
up:function(obj,item){
item.find(':text').val(item.find(':text').val() * 1 + 1);
$.fn.total(obj);
},
down:function(obj,item){
item.find(':text').val(item.find(':text').val() * 1 - 1);
$.fn.total(obj);
},
total:function(obj){
var sum = 0;
obj.each(function(i,item){
var price = $(item).find('.price_s').html() * 1;
var count = $(item).find(':text').val() * 1;
sum += price * count;
})

$('#total').html(sum.toFixed(2));
}
})

$('.test').money();
});
</script>
[code=html]
<div class="test">
<p>price:<span class="price_s">2</span></p>
<input class="min" name="" type="button" value="-" />
<input class="text_box" name="" type="text" value="10" />
<input class="add" name="" type="button" value="+" />
</div>

<div class="test">
<p>price:<span class="price_s">3</span></p>
<input class="min" name="" type="button" value="-" />
<input class="text_box" name="" type="text" value="10" />
<input class="add" name="" type="button" value="+" />