JavaScript插入DOM练习

廖雪峰JavaScript教程:插入DOM练习

<!-- HTML结构 -->
<ol id="test-list">
    <li class="lang">Scheme</li>
    <li class="lang">JavaScript</li>
    <li class="lang">Python</li>
    <li class="lang">Ruby</li>
    <li class="lang">Haskell</li>
</ol>

按字符串顺序重新排序DOM节点。

有自己实现的,也有评论看的,稍作记录。
实现1:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
    function sorotList(){
        var testlist = document.querySelector('#test-list');
        // var testlist = document.getElementById('test-list');
        var aLi = document.querySelectorAll('.lang');
        var arr = Array.prototype.slice.call(aLi);
        arr.sort((x, y) => x.textContent > y.textContent);
        arr.forEach( (x) => { testlist.appendChild(x) } );
    }
    </script>
</head>
<body>
    <button type="button" onclick="sorotList()">Run</button>
    <!-- HTML结构 -->
    <ol id="test-list">
    <li class="lang">Scheme</li>
    <li class="lang">JavaScript</li>
    <li class="lang">Python</li>
    <li class="lang">Ruby</li>
    <li class="lang">Haskell</li>
</ol>
</body>
</html>

类似的实现:

    function sorotList(){
        var arr = [];
        var testlist = document.getElementById('test-list');
        for (var i=0; i<testlist.children.length; i++) {
            arr.push(testlist.children[i]);
        }
        arr.sort((x, y) => {return x.innerText > y.innerText;});
        for (var j of arr) {testlist.appendChild(j)};
        // arr.forEach( (x) => testlist.appendChild(x));
    }

实现2(正则表达获取innerHTML,简洁):

    function sorotList(){
        var testlist = document.querySelector("#test-list");
        var arr = testlist.innerHTML.match(/<li.+?li>/g);
        testlist.innerHTML=arr.sort().join("")
    }

实现3(冒泡,不大好):

    function sorotList(){
        var list = document.getElementById('test-list');
        var length = list.children.length;
        for(var i = 0;i<length;i++){
            for(var j = i+1;j<length;j++){
                if(list.children[i].innerText>list.children[j].innerText){
                list.insertBefore(list.children[j],list.children[i]);
                }
            }
        }
    }
posted @ 2017-03-09 23:12  Eliefly  阅读(610)  评论(0编辑  收藏  举报