dataTables提醒大多数

时间:2016-08-19 12:40:53

标签: javascript jquery datatables

我有一个简单的表格,其中第一列为'公司',另外5列为'天',即二进制'1'或'0'

使用DataTables我试图获取5天内最多'1s'的公司/公司名称(第1列):

<table id="table" class="responstable" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
  <th scope="col">Company</th>
  <th scope="col">Day 1</th>
  <th scope="col">Day 2</th>
  <th scope="col">Day 3</th>
  <th scope="col">Day 4</th>
  <th scope="col">Day 5</th>
</tr>
</thead>
<tbody>
<tr>
  <td>Company1</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">1</td>
  <td align="center">0</td>
  <td align="center">1</td>
</tr>
<tr>
  <td>Company2</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">1</td>
</tr>
<tr>
  <td>Company3</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">1</td>
</tr>
<tr>
  <td>Company4</td>
  <td align="center">1</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">1</td>
</tr>
<tr>
  <td>Company5</td>
  <td align="center">1</td>
  <td align="center">1</td>
  <td align="center">0</td>
  <td align="center">0</td>
  <td align="center">0</td>
</tr>
</tbody>
</table>
<br/>
<input id="btnSubmit" type='button' value='Alert Rows'>

我将包含我的javascript,目前只计算总行数,所以没那么多帮助。

<script type="text/javascript">
$(document).ready(function() {

    $("#btnSubmit").click(function(){

        var table = $('#table').DataTable();

        var rowCount = table.rows()[0].length;

        for (var row=0;row<rowCount;row++) {

            //Not sure what to do here

        }
        alert(rowCount); //I need this to be company / companies name from 1st column.
        });
});
</script>

1 个答案:

答案 0 :(得分:0)

如果您想计算行中1的数量,可以使用rows().every()来迭代值。

要知道每行可以添加数值1,请尝试以下代码:

$(document).ready(function() {

   var table= $('#table').DataTable();

   $('#btnSubmit').click( function () {

       table.rows().every(function(){
         //Sum the values
         var count =  parseInt(this.data()[1]) + parseInt(this.data()[2]) + parseInt(this.data()[3]) + parseInt(this.data()[4]) + parseInt(this.data()[5]);
         //Get Company
         var company = this.data()[0];

         alert("The Company: " + company + " have " + count.toString() + " 1s" );
       });   

    });
});

结果: https://jsfiddle.net/cmedina/7kfmyw6x/88/