从顶层到底层对 DOM 节点数组进行排序
我有一个 DOM 节点数组(一个 javascript 数组,而不是 jQuery 对象),它充当处理它们的函数的队列。该数组可能包含具有父/子、祖父母/子等关系的元素。我总是希望首先处理更高级别的元素。我的第一个想法是在 javascript 中创建一个快速排序函数,但我知道如果我可以使用 javascript 的原生 Array.prototype.sort
方法,速度会更快。
我尝试了这样的方法:
domElements.sort(function (a, b) {
return $(a).find(b).length ? 1 :
$(b).find(a).length ? -1 :
0;
});
但它似乎并没有完美地排序。有时我仍然会在父母之前拥有子元素。为什么这不起作用?有没有办法用 javascript 的原生排序来做到这一点?
更新:在调查了答案中的方法后,我想知道它们的表现如何。 这里是结果。请随意调整,看看性能如何适合您。
I have an array (a javascript array, not a jQuery object) of DOM nodes that acts as a queue for a function I have that processes them. This array could potentially contain elements that have parent/child, grandparent/child, etc. relationships. I always want higher-level elements to be processed first. My first inclination was to whip up a quicksort function in javascript, but I knew it would be faster if I could use javascript's native Array.prototype.sort
method.
I tried it this way:
domElements.sort(function (a, b) {
return $(a).find(b).length ? 1 :
$(b).find(a).length ? -1 :
0;
});
But it didn't seem to sort it perfectly. I would still sometimes have child elements before their parents. Why doesn't this work? Is there a way to do this with javascript's native sort?
UPDATE: After surveying the methods in the answers, I wanted to know how they performed. Here are the results. Feel free to tweak and see how the performance is for you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 jQuery 的
unique
方法节省一些时间:http://api. jquery.com/jQuery.unique/You can save some time by using jQuery's
unique
method: http://api.jquery.com/jQuery.unique/(既然你要求我发布它。:-) )
你说过你想要父元素在数组中的子元素之前,但是你的代码
...返回
1
如果a
是b
的父级,这会将a
稍后放入数组比b
。所以我在想:
但是检查一个元素是否是另一个元素的后代是如此简单,我想知道你是否真的需要 allocate-a-jQuery-object-and-then-call-find:
工作示例 但请注意timmywil 的答案 ——尽管它做了一些不必要的工作(将兄弟姐妹排序,当你只关心父母时) /child),有一个预制的 jQuery 函数!
(Since you asked me to post it. :-) )
You've said you want the parent elements before the children in the array, but your code
...returns
1
ifa
is a parent ofb
, which will puta
later in the array thanb
.So I'm thinking:
But checking if an element is a descendant of another element is so straight-forward, I wonder if you really need the allocate-a-jQuery-object-and-then-call-find:
Working example But note timmywil's answer — even though it does a bit of unnecessary work (putting the siblings in order, when all you care about is parent/child), there's a pre-baked jQuery function for that!
看来我混合了一个否定号:
似乎有效。
It looks like I mixed around the negative sign on the one:
Seems to work.
根据源代码顺序对文档中的随机元素进行排序将
将子节点和兄弟节点保持在适当的位置。
Sorting random elements in a document according to their source code order will
keep childnodes and siblings in their proper positions.