JavaScript數字排序
阿新 • • 發佈:2018-12-27
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #ul1{background:red;} #ul2{background: yellow;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文件</title> <script> window.onload=function() { var oBtn=document.getElementById('btn1'); var oUl=document.getElementById('ul1'); oBtn.onclick=function() { //獲取ul1裡面所有的li var aLi=oUl.getElementsByTagName('li'); //appendChild //1.先移出父級 //2.新增到新的父級 //oUl2.appendChild(aLi[0]); var arr=[]; //1.轉成陣列 for(var i=0;i<aLi.length;i++) { arr[i]=aLi[i]; } //2.陣列排序 arr.sort(function(li1,li2){ return parseInt(li1.innerHTML)-parseInt(li2.innerHTML); }); //3.重新插入 for(var j=0; j<arr.length;j++) { oUl.appendChild(arr[j]); } } }; </script> </head> <body> <input id="btn1" type="button" value="移動Li" /> <ul id="ul1"> <li>32</li> <li>12</li> <li>89</li> <li>9</li> <li>18</li> </ul> </body> </html>