jQuery: 添加 class 到相同索引的兄弟行列

jQuery: add class to sibling rows columns of same index

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

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

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

对不起我的英语。

在您的 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;
}

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

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

我想给已经有水平 class 的列添加 "vertical" 属性,我这样做是好是坏?