javascript中li标签的排序和数组sort的用法
转:
javascript中li标签的排序和数组sort的用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<!DOCTYPE html> <html xmlns= "http://www.w3.org/1999/xhtml" > <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <title></title> <script type= "text/javascript" > window.onload = function () { var oBtn = document.getElementById( "btnChange" ); var oUl1 = document.getElementById( "ul1" ); oBtn.onclick = function () { var aLi = oUl1.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.innerText); var n2 = parseInt(li2.innerText); return n1 - n2; }); for ( var i = 0; i < aLi.length; i++) { oUl1.appendChild(arr[i]); } } } </script> </head> <body> <input type= "button" name= "" value= "移动" id= "btnChange" /> <ul id= "ul1" > <li>5</li> <li>2</li> <li>9</li> <li>4</li> <li>7</li> </ul> </body> </html> |