表格页脚,数字和平均百分比

时间:2017-05-18 18:57:19

标签: javascript jquery

我的html表看起来像这样:

      |       H1        |
  H1  |-----------------|
      |  H2  |    H2    |
------------------------|
Text  |Number|Percentage|
------------------------|
Text  |Number|Percentage|
------------------------|
...

有没有办法添加" Total"页脚看起来像这样:

      |       H1        |
  H1  |-----------------|
      |  H2  |    H2    |
------------------------|
Text  |Number|Percentage|
------------------------|
Text  |Number|Percentage|
------------------------|
...
------------------------|
Total:|Sum   |Avg prcntg|
------------------------|

使用JS,它会考虑单元格的类别(百分比,数字)并相应地计算列的总数?

有一些类似的解决方案,但我是JS(和HTML)的新手,并且不能自己修改它们。如果你在解决方案中提出一些意见,我会非常感激,所以我实际上可以学到一些东西:)

<table border="1"> 
<thead>
  <th rowspan="2">Header</th>
  <th colspan="2">Header</th>
  <tr>
    <th>Numbers</th>
    <th>Percentages</th>
  </tr>
</thead>
<tbody>
  <tr>
  <td>Text</td>
  <td class="number">1</td>
  <td class="percentage">30</td>
  </tr>
  <tr>
  <td>Text</td>
  <td class="number">2</td>
  <td class="percentage">40</td>
  </tr>
</tbody>  
<tfoot>
  <td>Total:</td>
  <td class="result"></td>
  <td class="result"></td>
</tfoot>
</table> 

修改

好的,我在其他解决方案上稍微摆弄了一下,在这里我做了些什么:

var totals = [0, 0, 0, 0, 0];
var tbodyrows = $('#myTable tbody').find('tr').length;
$(document).ready(function() {
  var $dataRows = $("#myTable tbody tr");
  $dataRows.each(function() {
    $(this).find('.number').each(function(i) {
      totals[i] += parseInt($(this).text());
    });
  });
  $("#myTable tfoot td:not(:first-child)").each(function(i) {
    if ($(this).hasClass("result")) {
      $(this).text(totals[i]);
    }
    if ($(this).hasClass("perresult")) {
      $(this).text(totals[i] / tbodyrows);
    }
  });
});

JSFIDDLE

这有效,但是如果我想要制作页脚,而不是填充预制的页脚呢?

2 个答案:

答案 0 :(得分:1)

如果您想自己将总数添加到表中,您可能正在寻找类似jQuery的.append函数。一旦您计算了总计,这将允许您将新表格行添加到表格的末尾。链接到文档:http://api.jquery.com/append/


    // JavaScript: (comments below each line start with //)
    var tableHtml = ''; 
    // new empty string variable to put your table html in
    tableHtml += ''; 
    // this starts a new table row (tr), += adds more to the existing value
    tableHtml += 'Text'; 
    // this is the text column (cell)
    tableHtml += ''+numberTotal+''; 
    // the js number variable in a new cell
    tableHtml += ''+percentTotal+''; 
    // the js percent variable in a new cell
    tableHtml += ''; 
    // the end of a new table row
    $( "table" ).append(tableHtml); 
    // appends this html as a child of "table" or "tbody" if that works better

您可能需要使用上面的其他一些注释来获取总数,但我的答案显示了如何在实时加载页面后将其添加到表中。

答案 1 :(得分:0)

是的,可以这样做。您可以使用jquery获取元素并运行循环以查找总计和平均百分比,如下所示:

var numbers=$('.number')
var percentage=$('.percentage')
var avg=0;
var total=0;
for(var i=0;i<numbers.length;i++){
   total=total+parseInt(numbers.eq(i).text())
   avg=avg+parseInt(percentage.eq(i).text())
}
$('.result').eq(0).text(total)
$('.result').eq(1).text(percentage/numbers.length)
相关问题