标签:
appendChild 1.先把元素从原有的父级上删除 2.添加到新的父级
<title>无标题文档</title> <script> window.onload=function () { var oUl=document.getElementById(‘ul1‘); var oBtn=document.getElementById(‘btn1‘); oBtn.onclick=function () { var aLi=oUl.getElementsByTagName(‘li‘); var arr=[]; for(var i=0;i<aLi.length;i++) { arr[i]=aLi[i]; } arr.sort(function(li1,li2){ var n1=parseInt(li1.innerHTML); var n2=parseInt(li2.innerHTML); return n1-n2; }); for(var i=0;i<arr.length;i++) { oUl.appendChild(arr[i]); } } } </script> </head> <body> <input id="btn1" type="button" value="排序"/> <ul id="ul1"> <li>23</li> <li>9</li> <li>99</li> <li>82</li> <li>34</li> </ul> </body>
排序后:
例二
<title>无标题文档</title> <style> #ul1{background:green;} #ul2{background:yellow;} </style> <script> window.onload=function () { var oBtn=document.getElementById(‘btn1‘); var oUl1=document.getElementById(‘ul1‘); var oUl2=document.getElementById(‘ul2‘); oBtn.onclick=function () { var oLi=oUl1.children[0]; oUl2.appendChild(oLi); } } </script> </head> <body> <ul id="ul1"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <input id="btn1" type="button" value="移动"/> <ul id="ul2"> </ul> </body>
表格排序
<title>无标题文档</title> <script> window.onload=function () { var oTab=document.getElementById(‘tab1‘); var oBtn=document.getElementById(‘btn1‘); oBtn.onclick=function () { var arr=[]; for(var i=0;i<oTab.tBodies[0].rows.length;i++) { arr[i]=oTab.tBodies[0].rows[i]; } arr.sort(function(tr1,tr2){ var n1=parseInt(tr1.cells[0].innerHTML); var n2=parseInt(tr2.cells[0].innerHTML); return n1-n2; }); for(var i=0;i<arr.length;i++) { oTab.tBodies[0].appendChild(arr[i]); } }; }; </script> </head> <body> <input id="btn1" type="button" value="排序"/> <table id="tab1" border="1" width="500"> <thead> <td>ID</td> <td>姓名</td> <td>年龄</td> <td>操作</td> </thead> <tbody> <tr> <td>2</td> <td>张三</td> <td>24</td> <td></td> </tr> <tr> <td>1</td> <td>blue</td> <td>23</td> <td></td> </tr> <tr> <td>5</td> <td>李六</td> <td>27</td> <td></td> </tr> <tr> <td>4</td> <td>王五</td> <td>26</td> <td></td> </tr> <tr> <td>3</td> <td>李四</td> <td>25</td> <td></td> </tr> </tbody> </table> </body>
排序后:
标签:
原文地址:http://www.cnblogs.com/919czzl/p/4318568.html