递归下来的DOM树 [英] Recursion down DOM tree

查看:124
本文介绍了递归下来的DOM树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Crockford的JavaScript代码:Good Parts。

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;
        }

    };

我了解代码,除了 func(node)。我想这一点是通过节点作为函数 func 中的一个参数,但浏览器如何理解? 节点 func 可以是任何东西 - 所以当函数被调用时,它可以这样读取:

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);
          });

func 被传递时, walkDOM 将处理函数(att){...}(document.body) - 这不会有任何意义。那么为什么Crockford选择包括func(节点)?

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)?

推荐答案

看起来像我这样的 func

例如,如果我想为整个树中的每个节点提醒标签名称:

For example, if I wanted to alert the tag name for every node in the entire tree:

walkDOM(document.body, function(node) {
    alert(node.tagName);
});

在您的示例函数中:

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

...您已命名为节点参数到 att ,但这并不奇怪地在一个属性的名称中。当 node.getAttribute(att)被运行时,我会期待一个变量节点被定义,因为节点被设置为 att ...在该函数的范围内没有节点

... you have named the node parameter to att, but that doesn't magically make in a name of an attribute. I would expect a "variable 'node' is not defined" when node.getAttribute(att) is ran, because node is being set to att... there is no node in that function's scope.

这篇关于递归下来的DOM树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆