星空网 > 软件开发 > Java

javascript实现组合列表框中元素移动效果

  应用背景:在页面中有两个列表框,需要把其中一个列表框的元素移动到另一个列表框 。

   实现的基本思想:

  (1)编写init方法对两个列表框进行初始化;

  (2)为body添加onload事件调用init方法;

  (3)编写move(s1,s2)把s1中选中的选项移到s2;

  (4)编写moveAll(s1,s2)把s1中所有的选项都移到s2.

  (5)为按钮添加onclick事件。

 

javascript代码如下:

 1 <script type="text/javascript" language="javascript"> 2   //对下拉框信息进行初始化 3   function init() { 4     for (i = 0; i < 10; i++) { 5       var y = document.createElement("option");//增加一个元素option 6       y.text = '选项' + i; 7       var x=document.getElementById("s1");//根据ID找到列表框 8  9       x.add(y, null); //10 11     }12 13   }14 15   //把选中的选项移到另一边16   function move(s1, s2) {17     var index = s1.selectedIndex;18     if (index == -1) {19       alert("没有选中值");20       return;21     }22 23     s2.length++;24     s2.options[s2.length - 1].value = s1.options[index].value;25     s2.options[s2.length - 1].text = s1.options[index].text;//s1中当前选中的值赋给s2的最后一个元素26     s1.remove(index);//从s1中移除当前元素27   }28 29   //把一边的完全移到另一边30   function moveAll(s1, s2) {31     if (s1.length == 0) {32       alert("没有可用选择");33       return;34     }35     s2.length = s2.length + s1.length;36     for (var i = 0; i < s1.length; i++) {37       s2.options[s2.length - s1.length + i].value = s1.options[i].value;38       s2.options[s2.length - s1.length + i].text = s1.options[i].text;39     }40 41     s1.length = 0;42   }43 </script>


<body>代码:

 1 <body onload="init()"> 2   <table> 3     <tr> 4       <td><select id="s1" size=10 style="width:100"></select></td> 5  6       <td><input type="button" name="moveToRight" value=">" 7         onClick="move(s1,s2)"> <br> 8       <br> <input type="button" name="moveAllToRight" value=">>" 9         onClick="moveAll(s1,s2)"> <br> <input type="button"10         name="moveToLeft" value="<" onClick="move(s2,s1)"> <br>11       <br> <input type="button" name="moveAllToLeft" value="<<"12         onClick="moveAll(s2,s1)"></td>13       <td><select id="s2" name="s2" size=10 style="width:100"></select></td>14 15     </tr>16   </table>17 18 </body>

 




原标题:javascript实现组合列表框中元素移动效果

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流