2014-04-05 22 views
1

我正在使用以下代碼行來搜索表格的行,以檢查TD是否包含我迄今爲止工作正常的searchTerm。jQuery:按列搜索包含x的TD而不是按行

有沒有一種方法,而不是按行搜索我可以在這裏按列搜索? 原因是,在我的情況下,一行可以包含多次相同的值,但不是一個列,這是我需要在這裏。

我的表有一個標準的結構與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> 

提前,蒂姆非常感謝。

+0

使用'jQuery.index()'。 – raina77ow

+0

謝謝。我將如何在這裏應用它,以便它搜索所有列? (我的表格有一組固定的13列。) – user2571510

回答

1

你可以在你列循環和讀取使用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/

+0

非常感謝 - 這看起來不錯。我是對的,這在IE8中不被支持,如果有一種解決方法可以在IE8和IE9中使用這個工具嗎?我可以使用eq()來代替它嗎? – user2571510

+0

我必須檢查它,或者你可以使用selectivzr http://stackoverflow.com/questions/16873391/nth-child-doesnt-work-in-ie7-ie8 –

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

使用nth-child(myNumber)(例如:nth-child(6))只是檢查要在列中的TD。例如,列6.

當然,您可以指定一個類,只需要檢查<td>,然後使用與該類選擇器相關的每個類。

+0

感謝您的支持。 – user2571510

相關問題