首页 > 代码库 > 用js写两个列表数据转换并排序

用js写两个列表数据转换并排序

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>读取并修改元素内容</title>
    <style>
        div{
            display:inline-block;
        }
        div button{
            display:block;
        }
        div select{
            width:100px;
            height:85px;
        }
    </style>
    <script>
        //定义全局变量
        var lsel=null; //左边select
        var rsel=null; //右边select
        var opt=null;  //全部的值
        window.$ = function(selector){
            return document.querySelectorAll(selector);
        };
        window.onload = function(){
            rsel = $("#rsel")[0];
            lsel = $("#lsel")[0];
            opt = lsel.innerHTML;
        };
        function move(btn){
            switch(btn.innerHTML){
                case ‘&gt;&gt;‘:    //按两个大于键
                    rsel.innerHTML = opt;
                    lsel.innerHTML = "";
                    break;
                case "&gt;":        //大于键
                    mo(lsel,rsel);
                    break;
                case "&lt;":        //小于键
                    mo(rsel,lsel);
                    break;
                case "&lt;&lt;":    //两个小于键
                    lsel.innerHTML = opt;
                    rsel.innerHTML = "";
                    break;
            }
        }
        function mo(sel,unsel){
            //定义两个空列表
            var pul = [];
            var pol = [];
            //将移出那边选中的和未选中的分开
            if(sel.length!=0 && sel.innerHTML!=""){
                for(var i=0;i<sel.length;i++){
                    sel[i].selected?
                            pul.push(sel[i].innerHTML):
                            pol.push(sel[i].innerHTML);
                }
            }
            //将选中的加入移入的框内
            for(var j=0;j<unsel.length;j++){
                pul.push(unsel[j].innerHTML);
            }
            if(pul.sort()[0]==""){pul.shift()};

            //将两部分分别归位
            sel.innerHTML = "<option>" + pol.sort().join("</option><option>") + "</option>";
            unsel.innerHTML = "<option>" + pul.sort().join("</option><option>") + "</option>";
        }

    </script>
</head>
<body>
<div>
    <select id="lsel" size="5" multiple>
        <option>Argentina</option>
        <option>Brazil</option>
        <option>Canada</option>
        <option>Chile</option>
        <option>China</option>
        <option>Cuba</option>
        <option>Denmark</option>
        <option>Egypt</option>
        <option>France</option>
        <option>Greece</option>
        <option>Spain</option>
    </select>
</div>
<div>
    <button onclick="move(this)">&gt;&gt;</button>
    <button onclick="move(this)">&gt;</button>
    <button onclick="move(this)">&lt;</button>
    <button onclick="move(this)">&lt;&lt;</button>
</div>
<div>
    <select id="rsel" size="5" multiple></select>
</div>
</body>
</html>

本文出自 “探讨科学” 博客,请务必保留此出处http://xiaoxin901008.blog.51cto.com/10300691/1943180

用js写两个列表数据转换并排序