最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sum TD in TABLE - Stack Overflow

programmeradmin5浏览0评论
<table id="tab" border="1">
    <tr>
        <td>One</td><td>123</td><td></td><td>32</td>
    </tr>
    <tr>
        <td>Two</td><td>52</td><td></td><td>53</td>
    </tr>
    <tr>
        <td>Three</td><td>234</td><td></td><td>56</td>
    </tr>
</table>

$('#tab').click(function(){
   sum();
})

function sum(){
 //????
}

How is the best method for sum column from second and fourth TD and fill in to third TD for each TR?

LIVE: /

<table id="tab" border="1">
    <tr>
        <td>One</td><td>123</td><td></td><td>32</td>
    </tr>
    <tr>
        <td>Two</td><td>52</td><td></td><td>53</td>
    </tr>
    <tr>
        <td>Three</td><td>234</td><td></td><td>56</td>
    </tr>
</table>

$('#tab').click(function(){
   sum();
})

function sum(){
 //????
}

How is the best method for sum column from second and fourth TD and fill in to third TD for each TR?

LIVE: http://jsfiddle/bYf8C/

Share Improve this question asked Apr 18, 2013 at 14:27 marksoodrigmarksoodrig 391 silver badge3 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4
function sum(){
    $("tr").each(function(){
        var sum = parseFloat($(this).find("td:eq(1)").text()) + 
                  parseFloat($(this).find("td:eq(3)").text());
        $(this).find("td:eq(2)").text(sum);
    })
}

Here, have a fiddle: http://jsfiddle/bYf8C/10/

demo: http://jsfiddle/bYf8C/2/

$('#tab').click(function(){
   sum();
})

function sum(){
    $('#tab').find('tr').each(function(){
        var first = $(this).children('td:eq(1)').text(),
            second = $(this).children('td:eq(3)').text();

        $(this).children('td:eq(2)').html(function(){
          return parseInt(first) + parseInt(second);
        });
    });
}

As Bojangles suggested in the ments, children() is faster than find(), and :eq is faster than :nth-child. My edit reflects that.

Here it is:

$(function() {
  $('#tab').on('click', function sum() {
    $('tr', this).each(function(index, tr) {
      var td1, td3;
      td1 = parseInt(tr.children[1].textContent, 10);
      td3 = parseInt(tr.children[3].textContent, 10);
      tr.children[2].innerHTML = td1 + td3;
    });
  });
});

Example: http://jsbin./uvuzeq/1/edit

function sum(){
   $('#tab tr').each(function() {
      var number1 = parseInt($(this).find("td").eq(1).html()); 
      var number2 = parseInt($(this).find("td").eq(3).html());
      $(this).find("td").eq(2).html(number1 + number2)
   });
}

Fiddle: http://jsfiddle/bYf8C/11/

发布评论

评论列表(0)

  1. 暂无评论