jquery - 获取html表格的指定列中的元素 [英] jquery - get elements in a specified columns of an html table
问题描述
使用jquery,我想要获取html表格的指定列中的所有元素。请注意,它可以是多个列
例如,如果我有以下html表:
<表>
< 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
abc
我想得到1 ,3,a,c
我应该怎么做?什么是最有效的方法? (我遍历由一些报告实用程序生成的巨大表)
这是或多或少的泛型例子,索引作为数组:
var cellIndexMapping = {0:true,2:true};
var data = [];
$ b $(#MyTable tr)。each(function(rowIndex){
$(this).find(td)。each(function(cellIndex){$ b $ (cellIndexMapping [cellIndex])
data.push($(this).text());
});
});
$(#Console)。html(data.join(< br />));
测试案例: http://jsfiddle.net/yahavbr/FuDh2/
使用关联数组有更快的性能,据我所知搜索特定的项目这样的数组应该已经被优化了。
请注意,在JS中,第一个索引总是0,所以1 st 和3
Using jquery, I'd like to get all elements in a specified columns of an html table. Please note that it can be more than one column
For example, if I have the following html table:
<table>
<tr>
<td>
a
</td>
<td>
b
</td>
<td>
c
</td>
</tr>
<tr>
<td>
1
</td>
<td>
2
</td>
<td>
3
</td>
</tr>
</table>
which looks as following:
1 2 3
a b c
I would like to get 1, 3, a , c
How should I do it? What would be the most efficient way to do so? (I am traversing a huge table generated by some reporting utility)
Here is more or less generic example letting you define the desired indices as array:
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 />"));
Test case: http://jsfiddle.net/yahavbr/FuDh2/
Using associative array to have faster performance, as far as I know search for specific item in such array should be optimized already.
Note that in JS first index is always 0, so 1st and 3rd cells means indices 0 and 2.
这篇关于jquery - 获取html表格的指定列中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!