简单节点操作,live对象
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>json</title> <style type="text/css"> .m1{text-align: center;width: 100px;background: black;color:white;height: 20px;line-height: 20px;margin: 5px; } </style> </head> <body> <input type="button" value='add'/> <div id='m'> <div class='m1' onclick="a(this)">1</div> </div> <script> var button=document.getElementsByTagName("input"); button[0].addEventListener("click",function(){ var m=document.getElementById('m'); var lastChild=m.lastElementChild; var num=Number(lastChild.textContent); var new_div=lastChild.cloneNode(true); var new_content=num+1; var new_txt_node=document.createTextNode(new_content); new_div.replaceChild(new_txt_node,new_div.firstChild); if(new_content%2==0){ new_div.style.backgroundColor='red'; }else{ new_div.style.backgroundColor='black'; } m.appendChild(new_div); },false); function a(e){ alert(e.textContent); } </script> </body> </html>
getElementsByTagName() 所取得的对象是一个NodeList对象,而非node对象的数组
NodeList对象的一大特征就是它是一个Live对象
Live对象始终具有dom树实体的引用,对dom树做的变更也会在Live对象中得到体现
在做动态添加时 for中 尤需注意 防止死循环
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>json</title> <style type="text/css"> span{display: block;background: green;cursor: pointer;color:white;width:50px;height: 20px;margin: 5px;} </style> </head> <body> <div id='foo'> <span>first</span> <span>second</span> </div> <script> var spans=document.getElementsByTagName("span"); var foo=document.getElementById('foo'); console.log("span:"+spans+"---- length:"+spans.length+"---"+(spans instanceof NodeList)); //span:[object HTMLCollection]---- length:2---false chrome下 console.log("foo:"+foo+"---- length:"+foo.childElementCount+"---"+(foo instanceof NodeList)); //foo:[object HTMLDivElement]---- length:2---false var new_span=spans[0].cloneNode(); new_span.appendChild(document.createTextNode("three")); foo.appendChild(new_span); console.log(spans.length);//3 知道spans的变化 称为live对象 console.log(foo.childElementCount);//3 </script> </body> </html>

浙公网安备 33010602011771号