數據加載中……
          數組_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)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 交城县| 呼玛县| 古丈县| 甘泉县| 大冶市| 西乌珠穆沁旗| 宣恩县| 本溪市| 翁源县| 泊头市| 涞源县| 安达市| 新巴尔虎右旗| 大渡口区| 略阳县| 筠连县| 岳阳市| 马山县| 安福县| 陈巴尔虎旗| 扎鲁特旗| 明水县| 呼图壁县| 江川县| 宁乡县| 承德市| 新营市| 错那县| 汝南县| 秦皇岛市| 锡林郭勒盟| 民乐县| 新丰县| 仲巴县| 高邑县| 图们市| 金乡县| 汶川县| 嘉峪关市| 沈阳市| 克山县|