문제

I have a table with rows like this:

<tr>
    <th width="30"></th>
    <th width="30">Time</th>
    <th>Description</th>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">2.50</td>
    <td>I did this, and also that, then a little of something else.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Another description of time.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Yet one more item entered.</td>
</tr>
<tr class="total">
    <td><strong>Total:</strong></td>
    <td><strong>[calculate total here]</strong></td>
    <td>&nbsp;</td>
</tr>

I'm using jQuery and as part of a function that occurs when adding time, I need to add all the numbers in the td.time cells. But for the life of me, I'm not so good at writing loops and can't figure it out.

I just need the code for going through all the td.time cells and adding the numbers up. Once I have the total, I can handle inserting it in the [calculate total here] spot.

Thanks!

도움이 되었습니까?

해결책

Select the elements, and use the each method to loop them:

var tot = 0;
$('td.time').each(function(){
  tot += parseFloat($(this).text());
});

다른 팁

You can use :nth-child(2n) to go through the second items of all table rows...

var total = 0.0;
$('table tr td:nth-child(2n)').each(function(){
        val = parseFloat($(this).html());
        if (val > 0)total += val;
});
$('#result').html(total);

or since your time columns are classes the same, you could even...

var total = 0.0;
$('.time').each(function(){
        val = parseFloat($(this).html());
        if (val > 0)total += val;
});
$('#result').html(total);

http://jsfiddle.net/WsSVQ/3/

if your table have id="TestTable" and the TD with total time id="total_time" then

var total = 0;
$('#TestTable td.time').each(function(index) {
total = total + parseFloat(this.html());
});
$('#total_time').html(total);

$('td[class*="time"]')

This selects all the TD tags with class "time", if i'm correct.
Maybe thats what you want to use?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top