JQuery: How to select rows from a table

后端 未结 3 1306
不知归路
不知归路 2020-12-07 03:01

I have a scenario where I would like to select rows from a table depending upon the values in td

e.g. I have a table like this


   

        
相关标签:
3条回答
  • 2020-12-07 03:38

    Here's a selector that should work:

    Try it out: http://jsfiddle.net/N6TdM/

    var x = "Andy";
    var y = "Gates";
    
    var res = $("td:first-child:contains(" + x + ") + td:contains(" + y + ")");
    

    Note that this could fail if you have something like the following:

    FIRST:   Roberto       Rob
    SECOND:  Robertson     Roberts
    

    Searching for "Rob Roberts" would give two matches.

    0 讨论(0)
  • 2020-12-07 03:43
    $("tr").each(function (index) {
       if ($.trim($(this).find('td:eq(0)').text()) == x &&
           $.trim($(this).find('td:eq(1)').text()) == y) {
           $(this).closest('table').css('border', '1px solid red');​ // this should do it
       }
    }); 
    

    Alternatively, using .filter:

    $("tr").filter(function() {
        return $.trim($(this).find('td:eq(0)').text()) == 'John' &&
               $.trim($(this).find('td:eq(1)').text()) == 'Smith';
    }).closest('table').find('tr').css('border', '1px solid red');​
    

    Demo: http://jsfiddle.net/WhFbE/5/

    0 讨论(0)
  • 2020-12-07 03:43

    You can use the native DOM cells property on the HTMLTableRowElement to access the cells directly, rather than sending jQuery on a roundabout trip with listing all descendant cells and picking out one with the non-standard :eq selector.

    $('tr').each(function (index) {
        if (
            $(this.cells[0]).text().trim()===x &&
            $(this.cells[1]).text().trim()===y
        ) {
            ...
        }
    });
    

    though it probably won't make a serious performance difference. Another approach would be simply to maintain an array-of-arrays containing the pre-trimmed data to save even looking at the DOM.

    0 讨论(0)
提交回复
热议问题