有人能帮我理解下面的代码吗?

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