Alternate row colors when you have rowspan

后端 未结 2 1558
别跟我提以往
别跟我提以往 2020-12-19 02:21

I have this HTML:

相关标签:
2条回答
  • 2020-12-19 03:05

    The solution provided by @nick-craver doesn't work for tables with cells which use both the rowspan and colspan attributes. The modified code below accounts for this, though it does assume that the total number of tags and their colspan values are equal for all rows.

    Thanks for pointing me in the right direction though @nick-craver!

    // This the maximum number of columns in your table, E.g. In this case a column crossing the whole table would have colspan="3"
    
    var column_count = 3;
    
    $("table.altRow tr").filter(function() {
    
      // Adds row children and colspan values of those children
    
      var child_count = 0;
      $("td", this).each(function(index) {
        if ($(this).attr('colspan') != null) {
          child_count += parseInt($(this).attr('colspan'));
        } else {
          child_count += 1;
        }
      });
    
      return child_count == column_count;
    }).filter(':even').addClass('alt');
    
    $("tr.alt td[rowspan]").each(function() {
      $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    0 讨论(0)
  • 2020-12-19 03:13

    There may be a slicker way to do it, but here's one way:

    $("table.altRow tr").filter(function() { 
      return $(this).children().length == 3;
    }).filter(':even').addClass('alt'​​​​​​);
    
    $("tr.alt td[rowspan]").each(function() {
      $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });
    

    This uses a CSS class instead of the color, like this:

    .alt { background-color​: #DEDFDE; }​
    

    You can give it a try here, you can swap :even and :odd in the first code block to do whichever pattern you want (with the example, :odd doesn't illustrate it well, since that's the rows without rowspan cells).

    What this does is find the rows with all the cells, not partial rows, gets the odd or even ones of those and applies a class. Then the second pass looks at those rows, and if they have any rowspan="" cells it gets that .rowSpan (DOM property), minus one for the current row, and applies the class that many rows down, via .nextAll() and .slice().

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