QQ图片20160301105718.png效果图
jQuery.mathutils.js
(function($){
$.mathUtils = ({
sum: function(array){
var total = 0;
$.each(array,function(index,value){
value = $.trim(value);
value = parseFloat(value) || 0;
total += value;
});
return total;
},
average:function(array){
var total = $.mathUtils.sum(array);
var average = total / array.length;
average = average.toFixed(2);
return average;
}
});
})(jQuery)
插件调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.extend demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<table id="inventory">
<thead>
<tr class="one">
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Spam</td>
<td>4</td>
<td>2.05</td>
</tr>
<tr>
<td>Egg</td>
<td>12</td>
<td>4.32</td>
</tr>
<tr>
<td>Gourmet Spam</td>
<td>14</td>
<td>7.89</td>
</tr>
</tbody>
<tfoot id ="sum">
<td>Total</td>
<td></td>
<td></td>
</tfoot>
</table>
<script src="./js/jquery.mathutils.js"></script>
<script>
$(document).ready(function(){
var $inventory = $("#inventory tbody");
//var quantities = new Array("12","32","21");
var quantities = $inventory.find('td:nth-child(2)')
.map(function(index,qty){
return $(qty).text();
}).get();
var sum = $.mathUtils.sum(quantities);
$('#sum').find('td:nth-child(2)').text(sum);
var prices = $inventory.find('td:nth-child(3)')
.map(function(index,qty){
return $(qty).text();
}).get();
var average = $.mathUtils.average(prices);
$('#sum').find('td:nth-child(3)').text(average);
});
</script>
</body>
</html>
网友评论