jQuery:找到表中项目的所有外观

时间:2014-04-05 19:17:37

标签: jquery arrays loops for-loop find

我的表格如下所示。

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

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

我的表:

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

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

1 个答案:

答案 0 :(得分: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

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


这是编写代码以实现结果的方法:[学分应该转到 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

相关问题