开发者

jQuery: Count specific character in a table column

I have a HTML table where each row has two columns. First column is a capital letter and the second one is a brand name, like so:

A | Amazon

A | Apple

B | BMW

C | Chanel

etc. But whenever there are two brand names that has the same first capital letter I would like the table to look like this:

A | Amazon

    | Apple

B | BMW

C | Chanel

In other words, if there are more than one instance of each capital letter I would like to display only the first one. If I applied a class to the first col开发者_如何学编程umn, is there a way I could achieve this using jQuery?


You can do that with the each() function (assuming the class of your first column is leftCol):

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


Assuming the class you give to the first column is called 'letter':

var previousLetter = null;
$('table td.letter').each(function(i, el){
    var currentLetter = el.innerHTML;
    if (currentLetter == previousLetter) el.innerHTML = '';
    previousLetter = currentLetter;
});

Although, you don't have to assign a special class for this, you can just the same use $('table td:first-child')

Of course, these solutions assume only one table in the page, so it would be wiser to give your table an id and use $('#myTable td:first-child')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜