[英]Select and sort a column in a table using Javascript
I want to select a particular column of a table and sort it accordingly using Javascript (No frameworks or plugins). 我想选择一个表的特定列并使用Javascript(无框架或插件)对它进行相应的排序。 Could anyone help me regarding this?
有人可以帮我吗?
<table>
<thead>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data11</td>
<td>Data23</td>
<td>Data53</td>
<td>Data45</td>
</tr>
<tr>
<td>Data81</td>
<td>Data42</td>
<td>Data33</td>
<td>Data4854</td>
</tr>
<tr>
<td>Data84681</td>
<td>Data452</td>
<td>Data354</td>
<td>Data448</td>
</tr>
<tr>
<td>Data1846</td>
<td>Data25635</td>
<td>Data3232</td>
<td>Data44378</td>
</tr>
</tbody>
</table>
function sortTableByColumn(tableId,columnNumber) { // (string,integer)
var tableElement=document.getElementById(tableId);
[].slice.call(tableElement.tBodies[0].rows).sort(function(a, b) {
return (
a.cells[columnNumber-1].textContent<b.cells[columnNumber-1].textContent?-1:
a.cells[columnNumber-1].textContent>b.cells[columnNumber-1].textContent?1:
0);
}).forEach(function(val, index) {
tableElement.tBodies[0].appendChild(val);
});
}
In your page, add id to the table tag: 在您的页面中,将id添加到表标签:
<table id="myTable">
From javascript, use: 从javascript使用:
sortTableByColumn("myTable",3);
tBodies[0]
is used because there can be many. tBodies[0]
是因为可以有很多。 In your example there is only one. 在您的示例中,只有一个。
If we have var arr=[123,456,789]
, [].slice.call(arr)
returns a copy of arr. 如果我们有
var arr=[123,456,789]
,则[].slice.call(arr)
返回[].slice.call(arr)
的副本。
We're feeding it the html-rows-collection, found in tBodies[0]
of tableElement
. 我们正在向它提供html-rows-collection,该
tBodies[0]
在tBodies[0]
中tableElement
。
Then, we sort that array with an inline function that compares two array elements, here: rows ( <tr>
). 然后,我们使用一个内联函数对该数组进行排序,该函数比较两个数组元素,在这里是:行(
<tr>
)。
Using cells[columnNumber]
we access the <td>
s, and textContent
to access the text content. 使用
cells[columnNumber]
我们访问<td>
,并使用textContent
访问文本内容。 I've used columnNumber-1
so you can enter 3 for third column instead of 2, because the index of first element of an array (column 1) is 0... 我使用了
columnNumber-1
因此您可以在第三列而不是2处输入3,因为数组(第1列)的第一个元素的索引为0 ...
The forEach
goes through the elements of the array, which is by now in order, and appendChild
row to the tBody. forEach
遍历数组的所有元素(到现在为止是按顺序排列),并将appendChild
行附加到tBody。 Because it already exist, it just moves it to the end: moving the lowest value to the end, then moving the second lowest to the (new) end, until it ends with the highest value, at the end. 因为它已经存在,所以将其移到末尾:将最低的值移到末尾,然后将第二低的值移到(新)末尾,直到最后以最高值结束。
I hope this is what you want. 我希望这就是你想要的。 If so, enjoy!
如果是这样,请尽情享受!
Try using datatables you can get it from http://datatables.net its reallt easy to use. 尝试使用数据表,您可以从http://datatables.net获得数据,其易于使用。 depends on jQuery
取决于jQuery
$("table").dataTable();
boom! 繁荣! and its done.
和完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.