appendChild()常用功能。
代碼說明
<!DOCTYPE html><html> <head> <title>appendChild的第二種功能</title> <script> window.onload=function(){ var oUl1=document.getElementById("ul1"); var oUl2=document.getElementById("ul2"); var oBtn=document.getElementById("btn1"); oBtn.onclick=function(){ var oLi=oUl1.children[0]; oUl1.appendChild(oLi); } } </script> </head> <body> <ul id="ul1"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <input type="button" id="btn1" value="移動"> </body></html>用appendChild的第二種功能實現(xiàn)一個li按照內(nèi)容大小排序
<!DOCTYPE html><html> <head> <title>appendChild的第二種功能</title> <script> window.onload=function(){ var oUl1=document.getElementById("ul1"); var oBtn=document.getElementById("btn1"); oBtn.onclick=function(){ var aLi=oUl1.getElementsByTagName("li"); // aLi是一個元素集合,不是真正意義的數(shù)組,不能用sort方法,轉(zhuǎn)成數(shù)組再用sort排序 var arr=[]; for(var i=0; i<aLi.length; i++){ arr.push(aLi[i]); } arr.sort(function(li1,li2){ var n1=parseInt(li1.innerHTML); var n2=parseInt(li2.innerHTML); return n1-n2 }); for(var j=0; j<arr.length; j++){ oUl1.appendChild(arr[j]);//當(dāng)添加子元素的時候以前的元素已經(jīng)被刪除,所以不會出現(xiàn)重復(fù)元素 } } } </script> </head> <body> <ul id="ul1"> <li>12</li> <li>2</li> <li>30</li> <li>22</li> </ul> <input type="button" id="btn1" value="移動"> </body></html>以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選