數據加載中……
          數組_sort firstChild

          <html>
          <body>

          <script type="text/javascript">
          function sortkids(e) {
               // This is the element whose children we are going to sort
               if (typeof e == "string") e = document.getElementById(e);

               // Transfer the element (but not text node) children of e to a real array
               var kids = [];
               for(var x = e.firstChild; x != null; x = x.nextSibling)
                   if (x.nodeType == 1 /* Node.ELEMENT_NODE */) kids.push(x);

               // Now sort the array based on the text content of each kid.
               // Assume that each kid has only a single child and it is a Text node
               kids.sort(function(n, m) { // This is the comparator function for sorting
                             var s = n.firstChild.data; // text of node n
                             var t = m.firstChild.data; // text of node m
                             if (s < t) return -1;      // n comes before m
                             else if (s > t) return 1;  // n comes after m
                             else return 0;             // n and m are equal
                         });

               // Now append the kids back into the parent in their sorted order.
               // When we insert a node that is already part of the document, it is
               // automatically removed from its current position, so reinserting
               // these nodes automatically moves them from their old position
               // Note that any text nodes we skipped get left behind, however.
               for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
          }
          </script>

          <ul id="list"> <!-- This is the list we'll sort -->
          <li>one<li>two<li>three<li>four <!-- items are not in alphabetical order -->
          </ul>
          <!-- this is the button that sorts the list -->
          <button onclick="sortkids('list')">Sort list</button>

          </body>
          </html>

          posted on 2009-08-07 20:51 R99 閱讀(166) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 陆河县| 大同市| 乡城县| 平果县| 美姑县| 建宁县| 康保县| 田林县| 阳泉市| 义马市| 夏邑县| 栾城县| 大安市| 平南县| 三穗县| 汤原县| 巴中市| 定日县| 司法| 石景山区| 梁山县| 岳阳市| 汉川市| 湖口县| 白朗县| 沐川县| 渑池县| 普陀区| 嘉兴市| 连云港市| 南宁市| 启东市| 正蓝旗| 聂荣县| 龙海市| 兴业县| 泽库县| 滕州市| 同心县| 福州市| 长宁县|