问题
I'm not sure how else I could have framed my question, but I have a table with multiple header rows and their respective sub-rows. The sub-rows should add up and set the value of the header rows. How can I do this efficiently?
<table>
<tr>
<td>A</td> //header row
<td><input type="text"/></td>
</tr>
<tr>
<td>A1</td> //sub-row
<td><input type="text"/></td>
</tr>
<tr>
<td>A2</td> //sub-row
<td><input type="text"/></td>
</tr>
<tr>
<td>B</td> //header row
<td><input type="text"/></td>
</tr>
<tr>
<td>B1</td>//sub-row
<td><input type="text"/></td>
</tr>
<tr>
<td>B2</td>//sub-row
<td><input type="text"/></td>
</tr>
<tr>
<td>C</td> //header row
<td><input type="text"/></td>
</tr>
<tr>
<td>C1</td> //sub-row
<td><input type="text"/></td>
</tr>
</table>
Sub row A1
+ A2
should set the total in input of A
. B1
+ B2
should add up to B
and so on.
One way I can think of doing is this way:
<tr>
<td>A</td> //header row
<td><input type="text" id="a"/></td>
</tr>
<tr>
<td>A1</td> //sub-row
<td><input type="text" class="asub"/></td>
</tr>
<tr>
<td>A2</td> //sub-row
<td><input type="text" class="asub"/></td>
</tr>
var finalresult = 0,
$a = $('.asub'),
$ares = $('#a');
$.each($a, function(i) {
var aVal = parseFloat( $a.eq(i).value() );
if (aVal) {
finalresult += aVal;
$ares.val( finalresult ));
}
});
But I'll have to do this multiple times for each header row. Is there any better way?
回答1:
You could use the data attributes. You can access these with .data in jQuery.
An input element could be something like this <input type="text" data-parent="A" class="sub"/>
. This way you can loop the elements with the sub
class and read the parent to know which value to increase.
You can put the data-parent
attribute on the <tr>
or <td>
tag if you like.
Hope this helped.
[EDIT]: Added example
<tr class="parent-row">
<td>A</td>
<td><input type="text" value="0" id="A" /></td>
</tr>
<tr class="child-row">
<td>A1</td>
<td><input type="text" data-parent="#A" /></td>
</tr>
<tr class="child-row">
<td>A2</td>
<td><input type="text" data-parent="#A" /></td>
</tr>
And in JavaScript:
$('.child-row').each( function(i) {
var input = $(this).find('input');
var parent = input.attr('data-parent'); // Could use the [.data](http://api.jquery.com/data/) function.
$(parent).val(parseFloat($(parent).val())+1);
// If you need to add values of child-rows' input elements you could use the one below
// $(parent).val(parseFloat($(parent).val())+parseFloat(input.val()));
});
来源:https://stackoverflow.com/questions/20370382/addition-of-values-of-blocks-of-rows-in-table