gpt4 book ai didi

javascript - 显示子节点节点列表的最简单方法? (初学者)

转载 作者:行者123 更新时间:2023-11-29 21:41:52 24 4
gpt4 key购买 nike

我正在尝试导航 DOM 树并检索 html 注释并将它们显示在警告框中。据我所知,我的警告框一直为空。如何正确显示 nodeList 数组?我已经搜索了几个小时,但似乎找不到任何有意义的信息。

<!DOCTYPE html>
<html>
<head>
<title>Hidden Comments</title>
<h1 style="text-align:center">Hidden Comments</h1>
<script>
function concatComs(){
var c=document.getElementById('body');
var array=[];
for(var i=0;c.childNodes.length<i;i++){
if(c.childNodes[i].nodeType==8) array[i]=c[i];
}
alert(array.toString());
}
</script>
</head>
<body id="body" style="text-align: center">
<!--you-->
<h2>Find the hidden comments!</h2>
<p>Look closely and you'll find them!</p><!--found-->
<input type="button" value="Go!" onClick="concatComs()"/>
<!--them-->
</body>
</html>

最佳答案

你的 for 循环应该像这样开始:

for(var i=0; i < c.childNodes.length; i++){

此外,您可能希望将 c.childNodes[i] 添加到您的 array

function concatComs(){
var c = document.getElementById('body');
var array=[];
for(var i=0; i < c.childNodes.length; i++){
if(c.childNodes[i].nodeType==8) {
array.push(c.childNodes[i]);
}
}
var result = "";
for(i in array) {
result += array[i].textContent + " ";
}
document.write(result);
}
<div id="body" style="text-align: center">
<!--you-->
<h2>Find the hidden comments!</h2>
<p>Look closely and you'll find them!</p><!--found-->
<input type="button" value="Go!" onClick="concatComs()"/>
<!--them-->
</div>

关于javascript - 显示子节点节点列表的最简单方法? (初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32516376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com