<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
<body>
<div id="content">
<h1>html</h1>
<h1>php</h1>
<h1>javascript</h1>
<h1>jquery</h1>
<h1>java</h1>
</div>
<script type="text/javascript">
function clearText() {
var content=document.getElementById("content");
// 在此完成该函数
for(var i=0;i<content.childNodes.length;i++)
{
if(content.removeChild(content.childNodes[i])!=null)
{
document.write(content.childNodes[i].innerHTML+"节点清除成功<br>");
content.childNodes[i].innerHTML = null;
}
else
{
document.write(content.childNodes[i].innerHTML+"节点清除失败"+"<br>");
}
}
}
</script>
<button onclick="clearText()">清除节点内容</button>
</body>
</html>
for(var i=0;i<content.childNodes.length;i++){let willRemoveContent = content.childNodes[i].innerHTML;if(content.removeChild(content.childNodes[i])!=null){document.write(willRemoveContent +"节点清除成功<br>");// content.childNodes[i].innerHTML = null;}else{document.write(willRemoveContent+"节点清除失败"+"<br>");
if(content.removeChild(content.childNodes[i])!=null)
的时候已经removeChild了 child,然后下面又去获取 child 的 innerHTML
content.childNodes[i].innerHTML+"节点清除成功<br>"
// 这里已经将childNodes[i]移除了 if(content.removeChild(content.childNodes[i])!=null) { // 这里再去读取content.childNodes[i] 不合理 document.write(content.childNodes[i].innerHTML+"节点清除成功<br>"); content.childNodes[i].innerHTML = null; } else { document.write(content.childNodes[i].innerHTML+"节点清除失败"+"<br>"); }
试试这个:
let willRemoveContent = content.childNodes[i].innerHTML; if(content.removeChild(content.childNodes[i])!=null) { document.write(willRemoveContent +"节点清除成功<br>"); } else { document.write(willRemoveContent+"节点清除失败"+"<br>" );
吐槽一下慕课做的排版真是麻烦