梅开一片
2016-06-14 10:21
<!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++){
content.removeChild(content.childNodes[i]);
}
}
</script>
<button onclick="clearText()">清除节点内容</button>
</body>
</html>为何我这样写不能一次性清除节点内容呢
问答板块里浏览最多的问答可以帮你解决。
http://www.imooc.com/qadetail/56371
你这里有很多问题!1:content.childNodes.length这个长度在每循环一次都会改变,这也会导致你的i比content.childNodes.length大,所以删除不完。2:content.removeChild(content.childNodes[i]);干嘛要移除第i个呢?因为第i个不一定存在用你的方法,content.removeChild(content.childNodes[0]);这样也可以实现。
JavaScript进阶篇
469056 学习 · 22582 问题
相似问题