jQuery:计算表格列中特定字符的数量

3
我有一个HTML表格,每行都有两列。第一列是大写字母,第二列是品牌名称,如下所示:

A | Amazon

A | Apple

B | BMW

C | Chanel

等等。但是每当有两个品牌名称具有相同的首字母时,我希望表格看起来像这样:

A | Amazon

    | Apple

B | BMW

C | Chanel

换句话说,如果每个大写字母有多个实例,我只想显示第一个实例。如果我将一个类应用于第一列,是否可以使用jQuery实现这一点?

你能修改HTML以在每一行中添加一个类吗?如果可以的话,你也许能够实现一个非JS的解决方案。 - Andy E
2个回答

1

如果您的第一列的类是leftCol,则可以使用each()函数来实现:

$(document).ready(function() {
    var lastLetter = "";
    $(".leftCol").each(function() {
        var $this = $(this);
        var text = $this.text();
        if (text != lastLetter) {
            lastLetter = text;
        } else {
            $this.text("");
        }
    });
});

0
假设你给第一列的类名叫做“letter”:
var previousLetter = null;
$('table td.letter').each(function(i, el){
    var currentLetter = el.innerHTML;
    if (currentLetter == previousLetter) el.innerHTML = '';
    previousLetter = currentLetter;
});

虽然你不必为此分配特殊的类,但你仍然可以使用$('table td:first-child')

当然,这些解决方案假定页面中只有一个表格,因此最好给你的表格一个ID并使用$('#myTable td:first-child')


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接