叛逆达人的博客

创造机会的人是勇者;等待机会的人是愚者

« Mootools v1.11 中文手册破解了“先有鸡还是先有蛋”这个世界难题 »

select控件排序 可多选


在做项目的时候需要这个功能,在网上找了也没找到合适的,于是就自己写了个。
把核心代码提取出来,希望对大家有帮助。
<script language="javascript">
<!--
function move(sel, selIndex1, selIndex2)
{
    var selValue, selText;
    selValue = sel.options[selIndex1].value;
    selText = sel.options[selIndex1].innerText;
    sel.options[selIndex1].value = sel.options[selIndex2].value;
    sel.options[selIndex1].innerText = sel.options[selIndex2].innerText;
    sel.options[selIndex2].value = selValue;
    sel.options[selIndex2].innerText = selText;
}
function doMove(sel, action)
{
    var i, selIndexs = "", selArray;
    if((sel.selectedIndex == -1) || (action == "u" && sel.options[0].selected) || (action == "d" && sel.options[sel.length-1].selected))
        return;
    if(action == "u") {
        for(i = 0; i < sel.length; i++)
            if(sel.options[i].selected) {
                sel.options[i].selected = false;
                selIndexs += (i - 1) + ",";
                move(sel, i, i - 1);
            }
    } else {
        for(i = sel.length-1; i >= 0; i--)
            if(sel.options[i].selected) {
                sel.options[i].selected = false;
                selIndexs += (i + 1) + ",";
                move(sel, i + 1, i);
            }
    }
    selArray = selIndexs.split(",");
    for(i=0;i<selArray.length-1;i++)
        sel.options[selArray[i]].selected = true;
}-->
</script>
示例:
<form name="f" method="post">
<select id="sel" name="s" size="10" multiple="multiple" style="width:130px;">
<option value="1">select1</option>
<option value="2">select2</option>
<option value="3">select3</option>
<option value="4">select4</option>
<option value="5">select5</option>
<option value="6">select6</option>
<option value="7">select7</option>
<option value="8">select8</option>
<option value="9">select9</option>
</select>
<BR>
<input type="button" value="Up" onclick="doMove(this.form.s,'u')" />
<input type="button" value="Down" onclick="doMove(this.form.s,'d')" />
</form>
演示(按住Ctrl可多选):

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新评论及回复

最近发表