【问题标题】:Alternate row colors when you have rowspan具有行跨度时的替代行颜色
【发布时间】:2015-03-10 22:08:16
【问题描述】:

我有这个 HTML:

<table class="altRowTable">

<script type="text/javascript">
  $(document).ready(function() {
    $("table.altRow tr:odd").css("background-color", "#DEDFDE");
  });
</script>

这工作正常,直到我有一些包含 rowspan 的行(它在各行之间不一致)。

所以我有这样的东西(下面的“-”代表一个空格——在 SOF 中不能真正做表格:))

|---ID---|---name---|---Number---|   
|---1----|---joe----|-----1------|   
|--------|---tom----|-----2------|   
|---2----|---joe----|-----3------|   
|---3----|---joe----|-----4------|   
|---4----|---joe----|-----6------|   
|---5----|---joe----|-----5------|   
|--------|---tom----|-----3------|   

如何使行跨度内的所有行保持相同的背景色?

【问题讨论】:

  • 当你建表时,你能改变类名吗?
  • 棘手的问题。 James 建议手动使用类名可能是最简单的方法。
  • 呵呵,我没有得到问题。对我有好处吗? ;)

标签: jquery html


【解决方案1】:

可能有一种更巧妙的方法,但这里有一种方法:

$("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');
});

这使用 CSS 类而不是颜色,如下所示:

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

You can give it a try here,您可以在第一个代码块中交换 :even:odd 以执行您想要的任何模式(在示例中,:odd 不能很好地说明它,因为那是行 没有 rowspan 单元格)。

这样做是找到具有所有单元格的行,而不是部分行,获取其中的奇数或偶数并应用一个类。然后第二遍查看 那些 行,如果它们有任何 rowspan="" 单元格,它会得到 .rowSpan(DOM 属性),为当前行减一,并应用该类那么多行向下,通过.nextAll().slice()

【讨论】:

  • 真的很酷前。 @Nick 我喜欢我 +1
【解决方案2】:

@nick-craver 提供的解决方案不适用于包含同时使用 rowspan colspan 属性的单元格的表格。下面修改后的代码说明了这一点,尽管它确实假设所有行的标签总数及其 colspan 值都是相等的。

感谢@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');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多