【问题标题】:Find td with specific text, and operate on the ALL td's on its right?找到带有特定文本的td,并对其右侧的ALL td进行操作?
【发布时间】:2014-02-15 22:36:44
【问题描述】:

这似乎与我的上一个问题 (Find td with specific text, and operate on the td right after that one?) 有点相似,但实际上是不同的..

这次我有一张这样的桌子:

<table class="test">
  <tr>
    <td>Row 1</td><td>Text 1-1</td><td>Text 1-2</td> ...... <td>Text 1-n</td>
  </tr>
  <tr>
    <td>Row 2</td><td>Text 2-1</td><td>Text 2-2</td> ...... <td>Text 2-n</td>
  </tr>
  <tr>
    <td>Row 3</td><td>Text 3-1</td><td>Text 3-2</td> ...... <td>Text 3-n</td>
  </tr>
  <tr>
    <td>Row 4</td><td>Text 4-1</td><td>Text 4-2</td> ...... <td>Text 4-n</td>
  </tr>
  <tr>
    <td>Row 5</td><td>Text 5-1</td><td>Text 5-2</td> ...... <td>Text 5-n</td>
  </tr>
</table>

基本上它有行,现在它有无限数量的列。

我需要用特定的文本对td 进行右移,然后对其右侧的所有tds 进行操作。要查找的文本将始终来自最左侧的tds,因为它将是行标题文本。

例如,我可能想找到一个带有文本Row 3td,然后我需要将xyz 附加到这个td 右侧的所有tds 的文本中(其中包含文本Row 3) ..

因此,在我的示例中,td 右侧包含 Row 3 的所有 tds 都将更改其文本:

Text 3-1 --> Text 3-1xyz
Text 3-2 --> Text 3-2xyz
.
.
.
Text 3-n --> Text 3-nxyz

我该如何解决这个问题?

【问题讨论】:

  • 阅读手册以了解 jquery 的能力将是一个好的开始:api.jquery.com/category/traversing/tree-traversal DOM 是一棵树,而标准的树操作方法(包括查找附近的相关元素)正是您所需要的。
  • 使用相同,但不要使用next 使用nextAllsiblings jsfiddle.net/h4Txd/1
  • 谢谢.. nextAll() 成功了! :D .. 如果你回答,我会标记它!

标签: javascript jquery css


【解决方案1】:

还有其他类型的资源可以让您选择 DOM 上的元素,例如 nextAll()siblings(),基于您刚刚更改的代码:

$(".test td:contains(Row 3)")
.nextAll().text(function(){
    return $(this).text() + "xyz"
});

【讨论】:

    【解决方案2】:

    使用 jquery 你可以使用contains selector,但是不合适,使用jQuery.each()

    $("table.test td").each(function() {
      if ($(this).html() == "Text 2-1")
        $(this).append("xyz");
    });
    

    http://jsbin.com/IrEpeTE/1/edit

    对于行使用“eq()”,像这样得到第 5 行:

    $("table.test tr:eq(4) td").each(function() {
       if ($(this).html()!="Row 5")
           $(this).append("xyz");
    });
    

    或:

    $("table.test tr td").each(function() {
      if ($(this).parent().children().html()=="Row 5" && $(this).html()!="Row 5")
           $(this).append("xyz");
    });
    

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 2012-03-25
      • 2015-11-06
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多