我想使用firefox中内置的javascript控制台从网页中排序一些表行。该网站本身不提供字母排序,但数据库很大,我需要更快地找到它。
结构是这样的:
<table id="entries">
<tr>
<td>
<img />
DATA
</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>...</tr>
...
</table>
所以最后我想重新排序那些tr
- 按字母顺序排序 DATA 的元素
(使用Firefox搜索不起作用,因为它不会滚动到单词的位置,我需要找到多个具有相同名称的项目。)
答案 0 :(得分:3)
你的问题很通用,答案也是如此。
var table = document.querySelector("table");
//append the ordered nodes, wrapped in a DocumentFragment
//this will be the last task that will be run,
//although it's the first command here
table.appendChild(
//get the rows you want to sort and convert the NodeList into an Array
Array.from(table.querySelectorAll("tr"))
//fetch the data you want to sort by.
.map(row => {
//return an intermediate-representation that associates
//your row with the (now cached) data you want to sort by.
//fetching this data in the sort-function would be way more expensive
return {
target: row,
value: row.querySelector("td").textContent
}
});
//sort
.sort((a,b) => a.value.localeCompare( b.value ))
//concat the rows into a document-fragment
.reduce((frag, data) => {
frag.appendChild( data.target );
return frag;
}, document.createDocumentFragment())
);
答案 1 :(得分:1)
我做了不同的事情,但我真的很喜欢@Thomas的代码,所以我只想根据他的分辨率生成一个通用的tableSorter
函数。这可能非常有用,作为对表头元素单击事件的回调。
此函数有三个参数;
true
升序,则降序
function tableSorter(table,cellIndex,order){ // table object, cell index and order passed as arguments
var frag = [...table.rows].map(row => ({tr: row, data: row.cells[cellIndex].textContent.trim()}))
.sort((a,b) => order ? a.data.localeCompare(b.data) : b.data.localeCompare(a.data))
.reduce((frag,sorted) => (frag.appendChild(sorted.tr), frag),document.createDocumentFragment());
window.requestAnimationFrame(table.appendChild.bind(table,frag));
return table;
}
var myTable = document.getElementById("entries");
tableSorter(myTable,0,true);
<table id="entries">
<tr>
<td>
<img /> XDATA
</td>
<td>d</td>
<td>w</td>
<td>h</td>
</tr>
<tr>
<td>
<img /> ADATA
</td>
<td>p</td>
<td>e</td>
<td>q</td>
</tr>
<tr>
<td>
<img /> FDATA
</td>
<td>a</td>
<td>b</td>
<td>x</td>
</tr>
</table>