有人能帮我理解下面的代码吗?
Can someone help me to understand the following code?
本文关键字:代码 更新时间:2023-09-26
function talksAbout(node, string) {
if (node.nodeType == document.ELEMENT_NODE) {
for (var i = 0; i < node.childNodes.length; i++) {
if (talksAbout(node.childNodes[i], string))
return true;
}
return false;
} else if (node.nodeType == document.TEXT_NODE) {
return node.nodeValue.indexOf(string) > -1;
}
}
console.log(talksAbout(document.body, "book"));
这段代码我在雄辩的Javascript第no页找到。234. 如果有人能逐行解释就太好了。
DOM由不同类型的节点组成。Body、Div等是元素节点,input:text、text Area等是文本节点。函数talksAbout递归地遍历给定'body'元素节点的childNodes,直到找到值为"book"的文本节点。
function talksAbout(node, string) { // declares a function called talksAbout, which takes two parameters: node and string
if (node.nodeType == document.ELEMENT_NODE) { // checks if the passed in node is an "ELEMENT_NODE" - <body><div><span>etc
for (var i = 0; i < node.childNodes.length; i++) { // loops through all the child nodes of the passed in node
if (talksAbout(node.childNodes[i], string)) // recursively calls the function on each node
return true; // returns true if the function returns true
} // ends the for loop block
return false; // returns false
} else if (node.nodeType == document.TEXT_NODE) { // if the node is a TEXT node
return node.nodeValue.indexOf(string) > -1; // returns true if the passed in string is somewhere in this text node
} // ends ths else if block
} // ends the function block
console.log(talksAbout(document.body, "book")); // execute the function, passing in the body element, and a string "book", logging the result to the console
基本上,该函数查看页面上的TEXT中是否存在单词"book"—因此将不将<div class="book">
视为匹配
此代码在页面中搜索单词"book",如果找到则返回true。我认为代码是非常简单的理解和阅读。但是你需要知道这个才能理解(在页面底部)
http://www.w3schools.com/dom/dom_nodetype.asp相关文章:
- 从桌面读取python文件时高亮显示代码
- 如何将函数包装在函数中以避免代码重复
- 通过单击表单中的按钮,在代码生成中使用javascript生成字母数字代码
- 货币代码为欧元-金额的格式不应包含小数
- Regex代码只允许一个空格
- 如何将屏幕分辨率乘以 80%,然后在代码中使用
- 从var向代码隐藏函数传递值
- 如何动态插入jquery代码
- 如何在php变量中嵌入JQuery代码
- 代码不会验证
- 如何从rails中的代码中删除新行( )
- Angularjs代码未在匿名函数中运行
- 如何做到这一点,使代码在不传递条件后执行函数
- 如何在读取XLS/XLSX本地文件时,使用IE的javascript代码启用未标记为安全的ActiveX控件
- 面向对象的Javascript代码在IE7中不起作用
- 将 jQuery 代码添加到 Index.aspx 页面
- 为什么忽略了eval()代码中的语法错误
- 元素在我的代码中不会.fadeTo.Don'I don’我不知道;s错误的JavaScript、JQuery、H
- 如何轻松地将服务器端变量从Java代码转移到客户端代码
- 代码只能在jsfiddle中工作