如何用 jQuery 编写一个简单的前序 DOM 树遍历算法?

2024-01-29

我想获取这里找到的代码:http://www.jslab.dk/articles/non.recursive.preorder.traversal.part2 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。

任何想法?我知道递归需要 argument.callee 因为 jQuery 中的回调是匿名的,但我对 JQuery 太陌生,无法进一步了解它。

Thanks!


正如 Code Duck 指出的,jQuery 按源顺序、深度优先(或者,正如您所说的,预顺序)遍历节点。然而,contents只获取直接子节点,而不获取后代节点。尝试这个:

$(document).contents ().each (function processNodes ()
{
    if (this.nodeType == 3)
        doSomething (this); // do something with text node
    else
        $(this).contents ().each (processNodes);
});

作为旁白,arguments.callee被标记为弃用,因此命名(而不是匿名)函数

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用 jQuery 编写一个简单的前序 DOM 树遍历算法? 的相关文章

随机推荐