【问题标题】:jQuery: find all appearances of item in tablejQuery:查找表中项目的所有外观
【发布时间】:2014-04-05 19:17:36
【问题描述】:

我有一张如下所示的表格。

有没有一种方法可以搜索表格以查找某个项目(列 Cat)的所有出现,然后将下一列(列 Vol)中的值添加到数组中,如下例所示 + 显示 0 如果它没有出现在一列中?

注意:每个值在一列中只能出现一次。

我的桌子:

<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>

要求的结果:

var x = [8, 0, 5]  // example outcome when searching for "item1"
var y = [7, 7, 1]  // example outcome when searching for "item2"
var z = [0, 5, 3]  // example outcome when searching for "item3"

非常感谢您提供的任何帮助,蒂姆。

【问题讨论】:

    标签: jquery arrays loops for-loop find


    【解决方案1】:

    你可以这样做,

    var searchTerm = "item1"
    var result = $('#myTable td:contains(' + searchTerm + ')').map(function(){
                      return $(this).next('td').text(); 
                 }).get();
    
    console.log(result); //[8, 0, 5]
    

    DEMO

    请阅读以下内容以了解上述代码中发生了什么,


    这是编写代码以实现您的结果的方式:[Credits should go to Sphinx]

    var searchTerm = "item1";
    var result = [];
    $('#myTable tbody tr').each(function () {
        if ($(this).find('td:contains(' + searchTerm + ')').length === 0)
            result.push(0);
        else {
            result.push(+($(this).find('td:contains(' + searchTerm + ')').next('td').text()));
        }
    });
    
    alert(result); //[8, 0, 5]
    

    Sphinx's DEMO

    【讨论】:

    • 谢谢你 - 看起来很棒!如何调整它以仅在具有特定类别的 TD 中搜索?
    • @user2571510 好吧,我刚刚在发布此答案后看到了该要求,我们需要迭代每一行以构建您想要的结果。如果您确定要这样做,请告诉我,我我会为你写代码..
    • 如何调整它以仅在具有特定类别的 TD 中搜索?请使用此选择器来实现,$('#myTable td.className:contains(' + searchTerm + ')')
    • 这很棒 - 非常感谢,很抱歉之后更改它。
    • @Rajaprabhu Aravindasamy 你的方式很棒。但是如果某些项目没有显示在一行上,它不会返回 0。因此,我根据您的代码找到了另一种方法。 jsfiddle.net/sphnix/pGGR8
    猜你喜欢
    • 2017-05-07
    • 2015-10-21
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多