【问题标题】:How to select a table column with jQuery如何使用 jQuery 选择表格列
【发布时间】:2012-01-12 14:54:55
【问题描述】:

我想选择一个表格列,我只知道该列的标题文本。 (th.innerText)

我尝试了以下代码,但它不起作用:

ownerIndex = $('th:contains("Owner")').index();
$('table tr td:nth-child(ownerIndex)')

有什么想法吗?

【问题讨论】:

    标签: jquery html-table jquery-selectors


    【解决方案1】:

    好的。我找到了解决方案:

    $('table tr td:nth-child('+ownerIndex+')')
    

    【讨论】:

    • 如果每个单元格的 colspan=1,则此方法有效,但如果单元格的列跨度不同,则会中断。
    • 谢谢,我已经添加到您的想法中,以便为“table-layout:fixed”样式设置列宽。在这种情况下,我从 colgroup 中选择孩子,例如。 $('#plGrid colgroup col:nth-child(0)').css('width', '150px'); $('#plGrid colgroup col:nth-child(1)').css('width', '250px');
    • 制作那个 nth-child(1); nth-child(2)
    【解决方案2】:

    在上面的示例中,ownerIndex 需要增加 1 以匹配 nth-child 的索引,它从 1 而不是 0 开始。

    这是我的看法: http://jsfiddle.net/2xU8t/

    /* Set all the cells in columns with THEHEADING in the heading to red */
    
    // Find the heading with the text THEHEADING
    columnTh = $("table th:contains('THEHEADING')");
    
    // Get the index & increment by 1 to match nth-child indexing
    columnIndex = columnTh.index() + 1; 
    
    // Set all the elements with that index in a tr red
    $('table tr td:nth-child(' + columnIndex + ')').css("color", "#F00");
    
    // Set the heading red too!
    columnTh.css("color", "#F00"); 
    

    【讨论】:

    • 这是唯一真正正确的答案。其他人,包括得票最多的人,错过了.index() 将返回一个从零开始的索引(即第一列的索引是 0),而:nth-child 接受一个从 1 开始的参数(即第一列将是:nth-child(1)
    【解决方案3】:

    这似乎使用反引号而不是单引号起作用:

    $(`table tr td:nth-child(${ownerIndex})`)
    

    【讨论】:

      【解决方案4】:

      上面的例子对我不起作用,因为我的细胞没有相同的 cosplan,我找到了这个解决方案:

       $("table tr>td:nth-child(${ownerIndex})");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-01
        • 2011-05-28
        • 2011-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        • 1970-01-01
        相关资源
        最近更新 更多