2011-03-29 73 views
6

使用jquery,我想獲取html表格的指定列中的所有元素。請注意,它可以超過一列jquery - 獲取html表格的指定列中的元素

舉例來說,如果我有以下HTML表格:

<table> 
    <tr> 
    <td> 
     a 
    </td> 
    <td> 
     b 
    </td> 
    <td> 
     c 
    </td> 
    </tr> 
    <tr> 
    <td> 
     1 
    </td> 
    <td> 
     2 
    </td> 
    <td> 
     3 
    </td> 
    </tr> 
</table> 

看起來如下:

1  2  3 
a  b  c 

我想獲得1 ,3,a,c

我應該怎麼做?什麼是最有效的方法? (我正在遍歷由一些報告實用程序生成的巨大表格)

+1

請更改您的問題! – waqasahmed 2011-03-29 15:39:16

+0

如果你有多行? – 2011-03-29 15:39:33

+0

我第二@waqasahmed它是非常混亂的,因爲它是。 – Trufa 2011-03-29 15:39:53

回答

8

這裏或多或少通用的例子讓你定義所需的指數爲數組:

var cellIndexMapping = { 0: true, 2: true }; 
var data = []; 

$("#MyTable tr").each(function(rowIndex) { 
    $(this).find("td").each(function(cellIndex) { 
     if (cellIndexMapping[cellIndex]) 
      data.push($(this).text()); 
    }); 
}); 

$("#Console").html(data.join("<br />")); 

測試用例:http://jsfiddle.net/yahavbr/FuDh2/

使用關聯數組有更快的性能,據我知道搜索這樣的數組中的特定項目應該已經優化。

注意,在JS第一個索引始終爲0,所以1 ST和3 細胞意味着指數0和2

1

您可以使用選擇器使用nth-child來完成。以下是另一種方式。

$("TABLE").find("tr").each(function(){ 
    var tr = this; 
    $([0,2]).each(function(){ 
     alert($(tr[this]).html()); 
    }); 
}); 

對於第一和第三,你必須指定0,2

2
var table = $("table"); // Make this more accurate if there are multiple tables on the page 
var rows = table.find("tr"); // Will find too much if there are <tr> tags nested in each other 

for (var i=0; i=rows.length; ++i) { 
    var cells = rows.eq(i).find("td"); 
    var values = [cells.eq(0).text(), cells.eq(2).text()]; 
} 
+1

+1注意到前兩個選擇器 – 2011-03-29 15:50:59

12

可以使用:nth-child()選擇。

$("tr td:nth-child(1), tr td:nth-child(3)").css('color', 'red'); 
+0

的缺點有趣,有沒有辦法做到這一點,但有多種模式,沒有再遍歷整個細胞? – vondip 2011-03-29 15:48:30

+0

據我所知,除非要只選擇奇數行或偶數行,否則必須爲每列設置一個單獨的模式,在這種情況下,您可以使用:nth-​​child(odd)。 – Kaivosukeltaja 2011-03-29 15:54:37

0

你可以像這樣

var retorno=[]; 
linha=$("td:nth-child(1), td:nth-child(3)").clone().each(function(){retorno.push($(this).text())}); 

$.each(retorno,function(index, item) {$('#Console').append(item+', ');}); 

1使用克隆到不修改表,如果你刪除表後修改此行。 2看跌元素融入RETORNO陣列 3,使用每個打印單元控制檯內

你可以做太多這樣的。用一條線:

$("td:nth-child(1), td:nth-child(3)").clone().map(function(){ return $(this).text()}).get().join(','); 

地圖 - 創建陣列回報列 GET - 獲取數組 加入 - 符合separete昌陣列逗號和顯示

1,3,A,C

這是我能做的最好的。