jquery to find all exact td matches

前端 未结 5 1481
陌清茗
陌清茗 2021-02-09 00:31
$(\'#servertable td:eq(\' + server + \')\')

this finds only 1 (first I think) match, how to find all matches. btw. td:contains will not work for me.

5条回答
  •  离开以前
    2021-02-09 01:05

    eq expects a numerical index to only return a single row. If you want to match a td by its contents, you have to use the :contains selector. Saying "it doesn't work" and throwing it away is not the right approach to the problem, as the selector is (most likely) not at fault (Do note its case sensitive, which might be it...)

    Anyhow, if you have a table like this:

    Hello World
    World Hello
    Hello Hello

    This jQuery code:

    $(function() {
        $("td:contains('Hello')").css('color','red');
    });
    

    Will turn all cells with "Hello" to red. Demo.

    If you need a case insensitive match, you could do this, using the filter function:

    $(function() {
        var search = 'HELLO'.toLowerCase();
        $("td").filter(function() {
            return $(this).text().toLowerCase().indexOf(search) != -1;
        }).css('color','red');
    });   
    

    If you need to match the exact contents of the cell, you could use something similar to the above:

    $(function() {
        var search = 'HELLO'.toLowerCase();
        $("td").filter(function() {
            return $(this).text().toLowerCase() == search;
        }).css('color','red');
    });
    

    The above is case insensitive (by turning both the search and the contents to lower case when comparing) otherwise you can just remove those if you want case sensitivity. Demo.

提交回复
热议问题