這是「Eloquent JavaScript」一書中示例的一個修改版本。需要了解爲什麼它總是返回「true1」。這個想法是在DOM中找到某個文本,但即使我給出了HTML中不存在的文本,仍然會在控制檯上獲得「true1」。爲什麼此函數總是返回「true1」
請幫助
我的HTML文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> My first JS page</title>
<script src="script1.js"></script>
</head>
<body>
<h1>My first page</h1>
<p> Hello , I am Mehdi and this is my first page</p>
<p> And this is the second paragraph on this page and</p>
</body>
<script>console.log(talksAbout(document.body, "Tester123"));</script>
</html>
我的JavaScript文件
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 "true1";
}
return "false1";
}else if(node.nodeType == document.TEXT_NODE){
return node.nodeValue.indexOf(string) > -1;
}
}
你用瀏覽器工具調試過代碼嗎? –
''true1'''''''''(字符串)都是'true'(boolean),所以不管'塊。 –