【问题标题】:jQuery: find TDs containing x by column instead of by rowjQuery:按列而不是按行查找包含 x 的 TD
【发布时间】:2014-05-18 05:52:26
【问题描述】:

我正在使用以下几行来搜索表的行,以检查 TD 是否包含我的 searchTerm 到目前为止工作正常。

有没有一种方法可以在这里按列搜索而不是按行搜索? 原因是在我的情况下,一行可以包含多次相同的值,但不是我需要的列。

我的表有一个标准的结构,包括 thead 和 tbody,如果需要,我可以添加一个 colgroup 或类。

我的 JS:

var searchTerm = "myText"
var result = new Array();
$('#myTable tbody tr').each(function() {
    result.push(+($(this).find('td:contains(' + searchTerm + ')').next('td').text()));
});
alert(result);

我的桌子:

<table id="myTable">
    <thead>
        <tr>
            <th class="myHeader">Cat 1</th>
            <th>Vol 1</th>
            <th class="myHeader">Cat 2</th>
            <th>Vol 2</th>
            <th class="myHeader">Cat 3</th>
            <th>Vol 3</th>
            //...
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>item1</td><td>8</td><td>item2</td><td>7</td>
        </tr>
        <tr>
            <td>item3</td><td>5</td><td>item2</td><td>7</td>
        </tr>
        <tr>
            <td>item2</td><td>1</td><td>item1</td><td>5</td><td>item3</td><td>3</td>
        </tr>
        //...
    </tbody>
</table>

提前非常感谢蒂姆。

【问题讨论】:

  • 使用jQuery.index()
  • 谢谢。我将如何在这里应用它以便搜索所有列? (我的表有一组固定的 13 列。)

标签: jquery arrays loops each


【解决方案1】:
$('#myTable tbody tr:nth-child(myNumber)').each(function() {
  var tdInMyNumberColumnValue = $(this).val();
 //do stuff
}

使用nth-child(myNumber)(例如:nth-child(6))只检查您想要的列中的 td。例如,第 6 列。

当然,您可以只分配一个您想要检查的 &lt;td&gt; 类,并使用与该类选择器相关的 each。

【讨论】:

  • 也谢谢你。
【解决方案2】:

您可以在列上循环并使用nth:child 选择器读取每个单元格:

选择作为其父级的第 n 个子级的所有元素。

代码:

var searchTerm = "myText"
var result = new Array();
for (var index = 0; index < $('#myTable thead th').length; index++) {
    $('#myTable tbody td:nth-child(' + index + ')').each(function () {
        if ($(this).is(':contains(' + searchTerm + ')'))
        result.push(+($(this).next('td').text()));
    });
}
alert(result);

演示:http://jsfiddle.net/IrvinDominin/6Et6F/

【讨论】:

  • 非常感谢 - 这看起来很棒。 IE8 不支持此功能是否正确?是否有解决方法可以在 IE8 和 IE9 中都使用此功能?我可以用 eq() 代替吗?
  • 我必须检查一下,或者您可以使用 selectivzr stackoverflow.com/questions/16873391/…
猜你喜欢
  • 2011-01-10
  • 2012-12-22
  • 2014-05-25
  • 1970-01-01
  • 2011-05-08
  • 2018-03-15
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多