javascript中li标签的排序和数组sort的用法

<!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>

  

posted @ 2014-06-11 22:40  ICupid  阅读(980)  评论(0编辑  收藏  举报