Javascript jQuery如何按不同的列值计算表中的行数
如何按表列计算不同的表行 例如:Javascript jQuery如何按不同的列值计算表中的行数,javascript,jquery,html,Javascript,Jquery,Html,如何按表列计算不同的表行 例如: <table> <thead> <tr> <th>NAME</th> <th>TECHNOLOGY</th> </tr> </thead> <tbody> <tr> <td>john</td>
<table>
<thead>
<tr>
<th>NAME</th>
<th>TECHNOLOGY</th>
</tr>
</thead>
<tbody>
<tr>
<td>john</td>
<td>jQuery</td>
</tr>
<tr>
<td>mark</td>
<td>css</td>
</tr>
<tr>
<td>blah</td>
<td>css</td>
</tr>
<tr>
<td>abc</td>
<td>css</td>
</tr>
<tr>
<td>xyz</td>
<td>jQuery</td>
</tr>
</tbody>
</table>
在这里,我不知道该单元格中有什么技术,但我需要通过该技术获得行数
提前感谢在加载时调用下面的函数。检查一下这个JSFIDLE-
var byTechnology = {};
$("table tbody td:nth-child(2)").each(function () {
var tech = $.trim( $(this).text() );
if ( !(byTechnology.hasOwnProperty(tech)) ) {
byTechnology[tech] = 0;
}
byTechnology[tech]++;
});
console.log(byTechnology);
// {
// css: 3,
// jQuery: 2
// }
该函数构建一个名为map的hashmap。
然后,它在tbody中的每个tr的第二个单元格上迭代,并检查它是否存在于映射中。如果不是,则将其添加到hashmap中,计数为1。如果是,则将计数增加1。
我希望这能有所帮助。另一个途径可能是编写一个更通用的函数,用于计算使用某些技术的人 假设您使用jQuery,并且您的表有一个id“tech”,您可以这样做
counter = function(textMatch){
count=0;
//loop through all <tr> s
$('#tech').find('tbody tr').each(function( index ) {
//if second <td> contains matching text update counter
if($($(this).find('td')[1]).text() == textMatch){
count++
}
});
return count;
}
console.log('Number of people using CSS is ' + counter('css'));
console.log('Number of people using CSS is ' + counter('jQuery'));
//and so on
计数器=函数(textMatch){
计数=0;
//循环遍历所有
$('tech')。查找('tbody tr')。每个(函数(索引){
//如果第二个包含匹配的文本更新计数器
if($($(this).find('td')[1]).text()==textMatch){
计数++
}
});
返回计数;
}
log('使用CSS的人数是'+计数器('CSS'));
log('使用CSS的人数是'+计数器('jQuery'));
//等等
检查这个问题:我认为它可以帮助您:)
function count()
{
var map = {};
$("tbody tr td:nth-child(2)").each(function(i, val){
var key = $(val).text();
if (key in map)
map[key]=map[key] + 1;
else
map[key] = 1;
});
var result='';
for(var key in map)
{
result += key + ':' + map[key] + '\n';
}
alert(result);
}
counter = function(textMatch){
count=0;
//loop through all <tr> s
$('#tech').find('tbody tr').each(function( index ) {
//if second <td> contains matching text update counter
if($($(this).find('td')[1]).text() == textMatch){
count++
}
});
return count;
}
console.log('Number of people using CSS is ' + counter('css'));
console.log('Number of people using CSS is ' + counter('jQuery'));
//and so on