【问题标题】:jQuery: add class to sibling rows columns of same indexjQuery:将类添加到相同索引的兄弟行列
【发布时间】:2017-01-12 08:40:12
【问题描述】:

我创建了查找包含数字的列的函数,然后在代码找到空列之前将类添加到它们和下一列。我还想将类添加到下面的列(下一行但具有相同索引的列),但我无法解决它。我已经尝试过 .parent() 方法,但我被卡住了,老实说我不知道​​我在做什么......这是我的代码

  $("table tbody tr td").each(function () {
    var num = $(this).text();
    if ($.isNumeric(num)) {
      $(this).addClass('word-' + num).nextUntil('td:empty').addClass('column-' + num);
    }
  });

这是显示我想要做什么的图片(红色字段)。

对不起我的英语。

【问题讨论】:

  • 您能否提供您的 html 并可能手动添加一个额外的表格来显示您想要的最终结果?现在的问题是,很难理解您希望实现的目标。
  • 这是我的 jsfiddle:jsfiddle.net/5yzLftu0 示例,数字 1 具有类 word-1,并且同一类被添加到同一行中的下一个 td。但我不知道如何将例如 word-3 类添加到 3 号以下的 te td。你现在明白了吗?

标签: jquery next siblings


【解决方案1】:

在您的 if 声明中,您可以添加以下内容:

JS Fiddle

var indexed = $(this).index() + 1; // Get column number
var row = $('tr').has(this); // Current row
row.nextAll('tr').each(function(e) {
  var cell = $(this).find('td:nth-child(' + indexed + ')');

  if(cell.text().length) {
      cell.addClass('word-' + num);
  } else {
      return false; // End loop if word is finished
  }

});

奖金

如果您想设置单词相交的样式(附加两个以“word-”开头的类,您可以执行以下操作:

/* Intersection */
[class^='word-'][class*=' word-'] {
  font-weight: bold;
  background: grey;
  color: white;
}

【讨论】:

    【解决方案2】:

    太好了,这就是我想要的:)

      $("td").each(function () {
        var num = $(this).text();
        if ($.isNumeric(num)) {
          $(this).addClass('word-' + num).nextUntil('td:empty').addClass('word-' + num);
          var indexed = $(this).index() + 1;
          var row = $('tr').has(this);
          row.nextAll('tr').each(function () {
            var cell = $(this).find('td:nth-child(' + indexed + ')');
            if (cell.text().length) {
              if (cell.find("[class*=word-]")) {
                cell.attr('vertical', 'word-' + num);
                cell.addClass('word-' + num);
              } else {
                cell.addClass('word-' + num);
              }
            } else {
              return false;
            }
          });
        }
      });
    

    我想在已经有水平类的列中添加“垂直”属性,我这样做是好是错?

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 1970-01-01
      • 2012-10-09
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多