欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解javascript appendChild()的完整功能

 更新時間:2018年08月18日 11:41:31   作者:666888  
這篇文章主要介紹了詳解javascript appendChild()的完整功能,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

appendChild()常用功能。

  • 平時我們用appendChild的時候,都是向父級上添加子元素
  • 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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論