Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - Recursion down DOM tree

This is code from Crockford's JavaScript: The Good Parts.

var results = [];

var walkDOM = function (node,func) {
        func(node);                     //What does this do?
        node = node.firstChild;
        while(node) {
            walkDOM(node,func);
            node = node.nextSibling;
        }

    };

I understand the code except for func(node). I guess the point is to pass node as a parameter in function func, but how will the browser understand it this way? node and func could be anything--so when the function is called it could read like this:

walkDOM(document.body,function(att) {
          node.getAttribute(att);
          results.push(node);
          });

When func is passed, walkDOM will process function(att) {...}(document.body)--which wouldn't make any sense. So why has Crockford chosen to include func(node)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes this tree traversal function makes sense since :

  • the function argument is supposed to know how to handle (any) nodes
  • the first call argument is supposed to be a supported node (not document.body for instance, if func doesn't know how to handle it)

That said, this algorithm still looks incorrect to me, as it only explores through the first sibling ; other siblings will be simply ignored. So I would recommend using this more traditional approach instead :

function walk(node, func) {
   var children = node.childNodes;
   for (var i = 0; i < children.length; i++)  // Children are siblings to each other
       walk(children[i], func);
   func(node);
}

Note that version is "deep first" (i.e. not calling call func() before processing children), but I'd rather recommend it since func is likely to change nodes. This way the processing of a parent will be able to consider the latest state of its already-processed children before issuing possibly un-appropriate changes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...