递归下来的DOM树

编程入门 行业动态 更新时间:2024-10-28 15:20:33
本文介绍了递归下来的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树

本文发布于:2023-10-15 12:21:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494315.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   DOM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!