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

DOM下复制节点下所有内容的方法
一个div,通过appendCHild方法加了一些组件,是checkbox,现在要在另一个div里把checkbox都复制过来,这怎么写?

------解决方案--------------------
1.遍历所有的checkbox
2.用cloneNode复制选中的checkbox.
3.插入t2
------解决方案--------------------
那要看你怎么组织HTML结构了。。
````
<label> xxx <input.... name= "c " /> </label>

然后document.getElementsByName( "c ")....遍历。。。
然后通过parentNode获得label
之后cloneNode..

------解决方案--------------------
<html>

<body>
<div id= "t1 "> </div> <div id= "t2 "> </div>

<input type= "button " onclick= "test() " value= "test1 "/>
<input type= "button " onclick= "test2() " value= "test2 "/>
<script>
function test(){
var t1=document.getElementById( "t1 ");
for(var i=0;i <10;i++){
var item=document.createElement( "input ");
item.type= "checkbox ";
item.id= "pid ";
item.name= "pid ";
item.value=i;

var pname = document.createTextNode(i);

t1.appendChild(item);
t1.appendChild(pname);
}


}
function test2(){

document.getElementById( "t2 ").innerHTML=document.getElementById( "t1 ").cloneNode(true).innerHTML
}
</script>
</body>
</html>