我想使用 Firefox 中的内置 JavaScript 控制台对网页中的一些表格行进行排序。该网站本身不提供按字母顺序排序,但数据库很大,我需要更快地找到东西。
结构是这样的:
<table id="entries">
<tr>
<td>
<img />
DATA
</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>...</tr>
...
</table>
所以最后我想重新排序这些tr
元素,按字母顺序排序DATA
(使用 Firefox 搜索不起作用,因为它不会滚动到单词的位置,并且我需要查找具有相同名称的多个项目。)
最佳答案
你的问题很笼统,所以答案就是这样。
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())
);
关于javascript - 如何使用 JavaScript 控制台对现有 DOM 元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38814096/