如何在jQuery中编写简单的预排序DOM树遍历算法? [英] How to write a simple preorder DOM tree traversal algorithm in jQuery?
问题描述
我想获取在此处找到的代码: http://www.jslab.dk/articles/non.recursive.preorder.traversal.part2
I'd like to take the code found here: http://www.jslab.dk/articles/non.recursive.preorder.traversal.part2
// HTML element
var root = document.documentElement;
recursivePreorder(root);
// Recusively find and handle all text nodes
function recursivePreorder(node) {
// If node is a text node
if (node.type == 3) {
// Do something with node
}
// else recurse for each child node
else {
for(var i=0; i<node.childNodes.length; i++)
recursivePreorder(node.childNodes[i]);
}
}
并将其转换为干净的jQuery.
and convert it into clean jQuery.
有什么主意吗?我知道递归需要arguments.callee,因为jQuery中的回调是匿名的,但是对于JQuery来说我还太陌生,无法继续使用它.
Any idea? I know recursion requires argument.callee since the callbacks in jQuery are anonymous, but I'm too new to JQuery to take it any further.
谢谢!
推荐答案
正如代码鸭所指出的那样,jQuery以源顺序,深度优先或您所称的顺序遍历节点.但是,contents
仅获取直接子节点,而不获取后代.试试这个:
As Code Duck pointed out, jQuery traverses nodes in source-order, depth-first - or, as you call it, pre-order. However, contents
only gets immediate children nodes, not descendants. Try this:
$(document).contents ().each (function processNodes ()
{
if (this.nodeType == 3)
doSomething (this); // do something with text node
else
$(this).contents ().each (processNodes);
});
顺便说一句,arguments.callee
被标记为不推荐使用,因此命名(而不是匿名)函数
As an aside, arguments.callee
is marked for deprecation, hence the named (as opposed to anonymous) function
这篇关于如何在jQuery中编写简单的预排序DOM树遍历算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!