下表使用颜色代码标识成功和失败:绿色表示成功,红色表示失败。
<table>
<thead>
<th>mon</th>
<th>tue</th>
<th>Wed</th>
</thead>
<tbody>
<tr>
<td>Tom</td>
<td class="miss"></td>
<td class="hit"></td>
<td class="miss"></td>
</tr>
<tr>
<td>Dick</td>
<td class="hit"></td>
<td class="hit"></td>
<td class="miss"></td>
</tr>
<tr>
<td>Harry</td>
<td class="miss"></td>
<td class="miss"></td>
<td class="hit"></td>
</tr>
</tbody>
</table>
下表总结了每个人的成功和失败
<table id="summary">
<thead>
<th>Name</th>
<th>Hits</th>
<th>misses</th>
<th>% compliance</th>
</thead>
<tbody>
<tr>
<td>Tom</td>
<td id="success"></td>
<td id="failed"></td>
<td id="percentage"></td>
</tr>
<tr>
<td>Dick</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Harry</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
下面的 Javascript 应该获取每个名称的类出现次数
$(function () {
var $rows = $("#summary tbody tr");
$rows.each(function (n) {
$("#failed").html('<b>' + $('tr .miss').length + '</b>');
$("#success").html('<b>' + $('tr .hit').length + '</b> ');
var total = $('.hit').length + $('.miss').length;
var completed = $('.hit').length;
var compliance = parseInt(completed * 100 / (total));
$("#percentage").html('<b>' + compliance + ' % </b>');
});
});
这是CSS
td.hit {
background-color:#76F33A !important;
}
td.miss {
background-color:#FF0F0F !important;
}
我想获取汇总表中每行的 CSS 类计数?
最佳答案
您不是根据行进行过滤,而是为整个表抓取它们。
您的代码 $('tr .miss').length
需要为 $(this).find('.miss').length
其中 this
是每个循环中的 tr
就我个人而言,我会这样做:
$("#stats tbody tr").each( function(){ //get the rows
var cells = $(this).find("td"); //get the cells
var name = cells.eq(0).text(); //name
var hit = cells.filter(".hit").length; //count the hits
var miss = cells.filter(".miss").length; //count the misses
var per = (hit / (hit + miss) * 100).toFixed(0); //calc percentage of hits
var row = "<tr><td>" + name + "</td><td>" + hit + "</td><td>" + miss + "</td><td>" + per + "</td></tr>"; //build row
$("#summary tbody").append(row); //add it to the new table
} );
.hit { background : green; }
.miss{ background : red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="stats">
<thead>
<th>Name</th>
<th>mon</th>
<th>tue</th>
<th>Wed</th>
</thead>
<tbody>
<tr>
<td>Tom</td>
<td class="miss"> </td>
<td class="hit"> </td>
<td class="miss"> </td>
</tr>
<tr>
<td>Dick</td>
<td class="hit"> </td>
<td class="hit"> </td>
<td class="miss"> </td>
</tr>
<tr>
<td>Harry</td>
<td class="miss"> </td>
<td class="miss"> </td>
<td class="hit"> </td>
</tr>
</tbody>
</table>
<table id="summary">
<thead>
<th>Name</th>
<th>Hits</th>
<th>misses</th>
<th>% compliance</th>
</thead>
<tbody>
</tbody>
</table>
关于javascript 计算每个表行的类出现次数并在另一个表中汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346605/