详解javascript appendChild()的完整功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

详解javascript appendChild()的完整功能

666888   2020-05-16 我要评论

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的第二种功能实现一个li按照内容大小排序

<!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是一个元素集合,不是真正意义的数组,不能用sort方法,转成数组再用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]);//当添加子元素的时候以前的元素已经被删除,所以不会出现重复元素
     }
    }
   }
  </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>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们