简体   繁体   English

使用Javascript / jQuery计算HTML表格的列或行中的唯一单元格

[英]Count unique cells in a column or row of an HTML table with Javascript/jQuery

Is there a simple way to count the unique cells in a column (or row) in an HTML table with jQuery or plain Javascript? 有没有一种简单的方法可以用jQuery或纯Java脚本计数HTML表格中某一列(或行)中的唯一单元格?

Example: (table with only one column) 示例:(表只有一列)

melon
banana
melon
strawberry

The counter would be 3. 计数器为3。

Try this: 尝试这个:

var a = {}, l = 0;
$('table tr td:first-child').each(function(){
    if (!a[$(this).text()]) {
        l++;
        a[$(this).text()] = true;
    }
});

alert(l);

For HTML: 对于HTML:

<table>
    <tr><td>melon</td><td></td></tr>
    <tr><td>banana</td><td></td></tr>
    <tr><td>melon</td><td></td></tr>
    <tr><td>strawberry</td><td></td></tr>
</table>

This will work for first column. 这将适用于第一列。 If you want to count values in second column you would use selector table tr td:first-child+td , for third table tr td:first-child+td+td , etc. 如果要对第二列中的值进行计数,则可以使用选择器table tr td:first-child+td ,对于第三table tr td:first-child+td+td等。

Working example: http://jsfiddle.net/7K64j/1/ 工作示例: http : //jsfiddle.net/7K64j/1/

Try this: 尝试这个:

var matches = [];
$('table td').each(function() {
  if(!$.inArray($(this).text(), matches)==-1) matches.push($(this).text());
});
alert(matches.length);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM