如何使用javascript控制台对现有DOM元素进行排序
How to sort existing DOM elements using a javascript console?
我想使用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())
);
我做了一些不同的事情,但我真的很喜欢@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>
相关文章:
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 在不使用JQuery的情况下隐藏DOM中的选定元素
- 如何在DOM元素上按类型构建此函数
- DOM元素和angular元素之间的主要区别是什么
- 当带有渲染器的DOM元素不在屏幕顶部时,移动了场景的坐标
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用jquery创建dom元素会导致ie9出现拒绝访问错误
- 通过AJAX侦听向DOM添加某些元素
- 如何在使用Ractive.extend()时引用DOM元素
- 在d3中向DOM元素添加了图像,但现在它赢得了't过渡
- Selenium无法在浏览器DOM中定位元素
- 如何'剪切'DOM元素并将其显示在其他位置
- 转换<a>使用jQuery将文本字符串转换为dom元素
- 从dom中删除任何元素后,Touchmove事件停止触发
- d3在数据更新时错误地附加了dom元素
- 访问VueJS中的DOM元素
- 在Meteor中如何查找DOM元素(渲染后)
- 找到元素DOM的根节点(阴影或光)的最佳方法是什么?
- 在querySelector:如何获得第一个和最后一个元素?dom中使用的遍历顺序