点滴积累【JS】---JS小功能(JS实现排序)
效果:
思路:
首先,获得用到的ID,在把得到的<li>数组添加到array数组里面,然后在进行array排序,排序完后再将array中的数据用appendChild添加到ul里面;
代码:
1 <head runat="server"> 2 <title></title> 3 <style type="text/css"> 4 ul li 5 { 6 background-color: #00FFFF; 7 } 8 </style> 9 <script type="text/javascript"> 10 window.onload = function () { 11 var oBtn = document.getElementById('btn'); 12 var oUl1 = document.getElementById('ul1'); 13 var oLiAll = oUl1.getElementsByTagName('li'); 14 var array = []; 15 oBtn.onclick = function () { 16 for (var i = 0; i < oLiAll.length; i++) { //把未排序前的li挨个添加到array里面 17 array[i] = oLiAll[i]; 18 } 19 array.sort(function (n1, n2) { //排序array 20 var num1 = n1.innerHTML; 21 var num2 = n2.innerHTML; 22 return num1 - num2; 23 }); 24 for (var j = 0; j < array.length; j++) { //把排序好的array挨个添加到ul里面 25 oUl1.appendChild(array[j]); 26 } 27 } 28 }; 29 </script> 30 </head> 31 <body> 32 <ul id="ul1" style="width: 200px;"> 33 <li>6</li> 34 <li>2</li> 35 <li>9</li> 36 <li>3</li> 37 <li>5</li> 38 <li>1</li> 39 <li>11</li> 40 <li>85</li> 41 <li>7</li> 42 <li>10</li> 43 </ul> 44 <input type="button" id="btn" value="排序" /> 45 </body>