數據加載中……
          數組_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 閱讀(164) 評論(0)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 鄂尔多斯市| 阳江市| 仙游县| 新郑市| 扬中市| 噶尔县| 启东市| 鲁甸县| 新密市| 靖边县| 大余县| 方城县| 仁布县| 若羌县| 龙游县| 和硕县| 达州市| 梁河县| 佛山市| 云安县| 宜州市| 广丰县| 丹江口市| 全州县| 巨野县| 抚顺县| 金秀| 威远县| 尤溪县| 芒康县| 奉新县| 富宁县| 宁安市| 囊谦县| 秦皇岛市| 西平县| 孙吴县| 沂南县| 广宁县| 青河县| 宁河县|