我正在构建一个接口,它会在检查输入时计算总数(基于相邻输入)。当一个输入被检查时,我得到的其他输入值在同一个<td>
,然后建立一个总计。我应该使用数组还是对象来构建摘要?
例子:http://jsfiddle.net/vdunm/1/
我需要建立总计为被检查,我只是似乎无法找到如何做的正确路径的所有复选框摘要(按名称分组)。
所以,如果你检查的第3行(2个FOOS和1条)我所要的输出是这个样子:
FOO: 100
BAR: 30
这里是我的HTML:
<table id="test">
<tr>
<td>
<input type="checkbox" name="id" size="20" value="100" />
<input type="text" name="name" size="20" value="FOO" />
<input type="text" name="cost" size="20" value="10.00">
<input type="text" name="quantity" size="20" value="1">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id" size="20" value="200" />
<input type="text" name="name" size="20" value="BAR" />
<input type="text" name="cost" size="20" value="10.00">
<input type="text" name="quantity" size="20" value="3">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id" size="20" value="300" />
<input type="text" name="name" size="20" value="FOO" />
<input type="text" name="cost" size="20" value="10.00">
<input type="text" name="quantity" size="20" value="9">
</td>
</tr>
</table>
的jQuery:
// when the id checkbox is clicked
$('table').delegate('input[name=id]', 'click', function(){
// set the total at 0
var totalCost = 0;
// loop through each checked line
$('input[name=id]:checked').each(function(){
// get the input values for this checked row
var thisRow = $(this).parent(),
person = thisRow.find('input[name=name]').val(),
qty = thisRow.find('input[name=quantity]').val(),
cost = thisRow.find('input[name=cost]').val();
// get total
var lineCost = cost * qty;
// add to the grand total
totalCost+=parseFloat(lineCost);
});
// output the total cost
$('#output').empty().append(totalCost);
});
我应该建立一个数组还是一个对象?我基本上只需要得到所有已经检查过的名字,并且显示每个名字的总和。我只需要一个正确的方向。
你想要什么?性能?最短的代码量?你可以去做很多不同的方式,但你想要做什么? – Niklas 2011-06-08 20:26:55
好问题,不会有大量的复选框,所以它不应该太重。我猜代码的可读性是可以拍摄的。 – jyoseph 2011-06-08 20:55:13