JavaScript控制listbox列表框的项目上下移动的方法
本文实例讲述了JavaScript控制listbox列表框的项目上下移动的方法。分享给大家供大家参考。具体分析如下:
这段JS代码可以控制listbox内的元素向上或者向下移动,这个功能非常有用。下面是详细的代码
functionlistbox_move(listID,direction){ varlistbox=document.getElementById(listID); varselIndex=listbox.selectedIndex; if(-1==selIndex){ alert("Pleaseselectanoptiontomove."); return; } varincrement=-1; if(direction=='up') increment=-1; else increment=1; if((selIndex+increment)<0|| (selIndex+increment)>(listbox.options.length-1)){ return; } varselValue=listbox.options[selIndex].value; varselText=listbox.options[selIndex].text; listbox.options[selIndex].value=listbox.options[selIndex+increment].value listbox.options[selIndex].text=listbox.options[selIndex+increment].text listbox.options[selIndex+increment].value=selValue; listbox.options[selIndex+increment].text=selText; listbox.selectedIndex=selIndex+increment; } //.. //.. listbox_move('countryList','up');//moveuptheselectedoption listbox_move('countryList','down');//movedowntheselectedoption
下面是详细的演示代码,可以在浏览器内使用
Clickbelowbuttonstoselectordeselectalloptionsfromselectbox.<br> <selectid="lsbox"name="lsbox"size="10"multiple=""> <optionvalue="1">India</option> <optionvalue="2">UnitedStates</option> <optionvalue="3">China</option> <optionvalue="4">Italy</option> <optionvalue="5">Germany</option> <optionvalue="6">Canada</option> <optionvalue="7">France</option> <optionvalue="8">UnitedKingdom</option> </select><br> <buttononclick="listboxMove('lsbox','up');">MoveUp</button> <buttononclick="listboxMove('lsbox','down');">MoveDown</button> <script> functionlistboxMove(listID,direction){ varlistbox=document.getElementById(listID); varselIndex=listbox.selectedIndex; if(-1==selIndex){ alert("Pleaseselectanoptiontomove."); return; } varincrement=-1; if(direction=='up') increment=-1; else increment=1; if((selIndex+increment)<0|| (selIndex+increment)>(listbox.options.length-1)){ return; } varselValue=listbox.options[selIndex].value; varselText=listbox.options[selIndex].text; listbox.options[selIndex].value=listbox.options[selIndex+increment].value listbox.options[selIndex].text=listbox.options[selIndex+increment].text listbox.options[selIndex+increment].value=selValue; listbox.options[selIndex+increment].text=selText; listbox.selectedIndex=selIndex+increment; } </script>
希望本文所述对大家的javascript程序设计有所帮助。