http://jsfiddle.net/PzBqX/4/
为了矫枉过正,这是为了以防您具有相同的表结构并希望在任何列中搜索任何数据集。
HTML:
<table>
<tr>
<th>Alarm</th>
<th>Fruit</th>
</tr><tr>
<td>OK</td>
<td>Apple</td>
</tr><tr>
<td>Missing</td>
<td>Orange</td>
</tr><tr>
<td>OK</td>
<td>Apple</td>
</tr>
</table>
JavaScript:
$(document).ready(function() {
var results = tallyResults($('table'), 'Fruit', Array('Apple', 'Orange'));
/*
{
Apple: 2,
Orange: 1
}
*/
});
function tallyResults(table, col, vals) {
var valsCount = { }
var columnIndex = null;
//-- init value object using vals array
$(vals).each(function(i, v) {
valsCount[v] = 0;
});
//-- get index of the column we are currently searching
table.find('tr th').each(function(i, v) {
el = $(this);
if (el.text() == col) {
columnIndex = el.index();
}
});
//-- tally all instances of the values we are searching
//-- for in the proper column index
table.find('tr td').each(function(i, v) {
el = $(this);
if (el.index() == columnIndex) {
t = el.text();
if(valsCount[t] != undefined) {
valsCount[t]++;
}
}
});
return valsCount;
}