2013-11-22 73 views
0

我有一个表,第二列有国家,我有很多的国家,但我需要显示有多少来自美国,有多少是来自日本。比较值jQuery和总结

我使用此代码有从列中的值,但 我如何比较和计算这个值?

var items=[]; 
//Iterate all td's in second column 
$('#MyTable>tbody>tr>td:nth-child(2)').each(function(){ 
    //add item to array 
    items.push($(this).text());  
}); 

,我需要显示到表

这里的底部,这是HTML

<table id="MyTable" width="620px;"> 
    <tbody> 
     <tr> 
      <td> </td> 
      <td class="country">US</td> 
      <td><a href="http://google.com" target="_blank">google.com</a></td> 
      <td>12/21/2012</td> 
     </tr> 
     <tr class="alt"> 
      <td> </td> 
      <td class="country">Japan</td> 
      <td><a href="http://google.info" target="_blank">google.info</a></td> 
      <td>12/21/2012</td> 
     </tr> 
     <tr> 
      <td> </td> 
      <td class="country">Japan</td> 
      <td><a href="http://google.info" target="_blank">google.info</a></td> 
      <td>12/21/2012</td> 
     </tr> 
     <tr class="alt"> 
      <td>Migration</td> 
      <td class="country">tokyo</td> 
      <td><a href="http://google.info" target="_blank">google.info</a></td> 
      <td>12/21/2012</td> 
     </tr> 
    </tbody> 
</table> 

应显示日本2,美国:1东京:1

+0

在绝对最低,我们需要一个什么样的在'$样品(这) .text()',但最好提供一些代表数据集的表格标记行。 – ajp15243

+0

不知道我得到这个:'有多少来自美国,有多少来自日本'。你在谈论国家,不是吗? – melancia

+0

@MelanciaUK - 我猜这应该是城市 – tymeJV

回答

0

既然你是使用jQuery,你可以看看这个小提琴:这你想要做什么:http://jsfiddle.net/QtBlueWaffle/LHK8h/2/

但是,你应该看看:http://www.w3schools.com/jsref/jsref_obj_array.asp

这里是我使用的代码:

var items = []; 
//Iterate all td's in second column 
$('#MyTable>tbody>tr>td:nth-child(2)').each(function() { 
    //add item to array 
    items.push($(this).text()); 
}); 

var countries = []; 
var countriesNumbers = []; 
for (var i = 0; i < items.length; i = i + 1) { 
    var index = countries.indexOf(items[i]); 
    if (index != -1) { 
     countriesNumbers[index] += 1; 
    } else { 
     countries.push(items[i]); 
     countriesNumbers.push(1); 
    } 

} 

// Build the resulting string 
var result = ""; 
for (var i = 0; i < countries.length; i += 1) { 
    result = result.concat(countries[i]).concat(":").concat(countriesNumbers[i]).concat(";"); 
} 
// Show the result 
$("#result").html(result); 

希望这有助于

+0

谢谢!看起来不错! – Darkcus

+0

@Darkcus:如果它符合你的需求,你可以接受答案。 – ThisIsSparta