日期:2014-05-16  浏览次数:20349 次

删除节点中的内容出现的问题。
代码如下:
<div id="one" style="background:#CCC;width:500px;height:300px;"></div>
<input type="button" value="add" id="btn1">
<input type="button" value="delete" id="btn2">
<script>
var add=document.getElementById("btn1");
var del=document.getElementById("btn2");
add.onclick=function(){
var po=document.getElementById("one");
var con=document.createElement("div");
con.innerHTML="hellow world!!";
po.appendChild(con);
}
del.onclick=function(){
var po=document.getElementById("one");
var children=po.childNodes;
for(i=0;i<children.length;i++){
po.removeChild(children[i]);
}
}

</script>

每次按下add按钮,就增加一个hellow world。每次按下delete就删除所有的hellow world。但是,为什么我每次按下delete不是删除所有的hellow world,而是一部分?


------解决方案--------------------
del.onclick=function(){
    var po=document.getElementById("one");
    var children=po.childNodes;

 for(i=children.length-1;i>=0;i--){
     alert(i)
        po.removeChild(children[i]);
        }
    }


应该从最后一个元素删除,如果从第一个删除的话 ,会改变原有dom的结构,索引都会改变的 
------解决方案--------------------
del.onclick=function(){
    var po=document.getElementById("one");
    var children=po.childNodes;
    while(children.length)  po.removeChild(children[0]);
}
//按你意思,可以简化成
del.onclick=function(){
    var po=document.getElementById("one");
    po.innerHTML="" 
}
------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
</style>
</head>

<body>
<div id="one" style="background:#CCC;width:500px;height:300px;"></div>
<input type="button" value="add" id="btn1">
<input type="button" value="delete" id="btn2">
<script type="text/javascript">
var add=document.getElementById("btn1");
var del=document.getElementById("btn2");
add.onclick=function(){
     var po=document.getElementById("one");
     var con=document.createElement("div");
     con.innerHTML="hellow world!!";
     po.appendChild(con);
    }
del.onclick=function(){
     var po=document.getElementById("one");
     var children=po.childNodes;
var p=children.length;
     for(i=0;i<p;i++){
         po.removeChild(children[0]);
        }
    }
</script>
</body>
</html>

3D模型导入 CanvasMatrix.js发动机 demo(一)