代码之家  ›  专栏  ›  技术社区  ›  Nelson Rothermel

jQuery选择具有特定标题的表单元格

  •  2
  • Nelson Rothermel  · 技术社区  · 15 年前

    我有一个带有“header”的表,用户可以使用常规tr标记(而不是th)。我需要找到标题“Col2”,然后在Col2下的每个单元格中添加一个锚。我能做到 $("td:contains('Col2'))

    <table>
      <tr>
        <td>Col1</td>
        <td>Col2</td>
      </tr>
      <tr>
        <td>Data1</td>
        <td>Data2</td>
      </tr>
      <tr>
        <td>Data3</td>
        <td>Data4</td>
      </tr>
    </table>
    

    变成:

    <table>
      <tr>
        <td>Col1</td>
        <td>Col2</td>
      </tr>
      <tr>
        <td>Data1</td>
        <td><a href="?Data2">Data2</a></td>
      </tr>
      <tr>
        <td>Data3</td>
        <td><a href="?Data4">Data4</a></td>
      </tr>
    </table>
    

    :first 只匹配第一个表中的第一行。

    更新:

    $('table').each(function(i, table) {
        $(table).find('tr:first > td:contains("Col2")').each(function() {
            var cellIndex = $(this).index() + 1;
    
            $(table).find('tr:not(:first) > td:nth-child(' + cellIndex + ')').wrapInner(function() {
                return $('<a />', { 'href': '?data=' + $(this).text() });
            });
        });
    });
    
    4 回复  |  直到 15 年前
        1
  •  3
  •   Nick Craver    15 年前

    你可以用 .index() .wrapInner(function) 这样地:

    var i = $("table tr td:contains('Col2')").index() + 1;
    $("table tr:gt(0) td:nth-child(" + i +")")​​​​​​​​​​​​​​​​​​​​​​​​​​​​​.wrapInner(function() {
        return $("<a />", { "href": "?" + $(this).text() });
    });​
    

    You can see an example here <td> "Col2" (基于0)然后使用 :nth-child() selector <td> .wrapInner() . 在那之后,我们只是返回结构来包装它们,通过 $(html, props) .

        2
  •  1
  •   programatique    15 年前

    您是否尝试过使用“:first”选择器(包括“not(:first)”)

    http://api.jquery.com/first-selector/

        3
  •  1
  •   gblazex    15 年前

    [ See it in action ]

    var index = $("table:first-child td:contains('Col2')").index() + 1;
    $("tr:not(:first) :nth-child("+index+")").each(function(){
       var old = $(this).html();
       $(this).html("<a href='?"+old+"'>"+old+"</a>");                                          
    });
    

        4
  •  0
  •   spinon    15 年前

    我会做以下工作:

    在标题行中搜索符合条件的列,然后获取列索引。然后选择表中从该列索引中的第二行开始的所有行。然后创建锚定。如果你需要帮助,我可以试着写一些代码。