jQuery:将类添加到同一索引的兄弟行列

时间:2016-09-05 00:59:27

标签: jquery next siblings

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

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

这是显示我想要做的图像(红色字段)。enter image description here

抱歉我的英文。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

很好,这就是我想要的:)

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

我想将“vertical”属性添加到已经有水平类的列中,我做得好还是错?