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(){
 //????
}

从第二个和第四个 TD 求和列并为每个 TR 填写到第三个 TD 的最佳方法是什么?

直播:http : //jsfiddle.net/bYf8C/

4

4 回答 4

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);
    })
}

在这里,有一个小提琴:http: //jsfiddle.net/bYf8C/10/

于 2013-04-18T14:32:59.330 回答
2

演示:http: //jsfiddle.net/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);
        });
    });
}

正如 Bojangles 在评论中建议的那样,children()比 快find(),而且:eq:nth-child. 我的编辑反映了这一点。

于 2013-04-18T14:30:56.950 回答
1

这里是:

$(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;
    });
  });
});

示例:http: //jsbin.com/uvuzeq/1/edit

于 2013-04-18T14:42:16.510 回答
0
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)
   });
}

小提琴:http: //jsfiddle.net/bYf8C/11/

于 2013-04-18T14:34:54.137 回答