JavaScript列表框双向操作与初始化函数集

作者:纸飞机

时间:2026-10-28

浏览:257

本文提供了一套完整的JavaScript函数集合,用于处理HTML列表框(select)的双向交互。涵盖从源列表添加不重复元素到目标列表、删除选中项、检测重复值、全选或单选指定项,以及根据逗号分隔数组初始化列表框等功能。代码适用于传统Web开发场景,帮助开发者快速实现复杂的列表数据管理逻辑。

文章目录

JavaScript列表框双向操作与初始化函数集

以下是实现列表框双向操作及初始化的JavaScript代码示例:

<script language="javascript">
/* 列表框互相操作函数集 */
//描述: 添加不重复列表框元素
function selAdd( srcList, dstList )
  {
var selectedIndex = new Array();
var count = 0;
for ( i=0; i<srcList.options.length; i++ ){
if ( srcList.options[i].selected ){
selectedIndex[count] = i;
count ++;
         }
     }                    
for ( j=0; j<selectedIndex.length; j++ ){
k = selectedIndex[j];
if ( chkDup( srcList.options[k].value, dstList )==false ){
&nbsp; dstList.options.length++;
var len = dstList.options.length-1;
dstList.options[len].value = srcList.options[k].value;
dstList.options[len].text = srcList.options[k].text;
         }
     }
 }
//描述: 删除列表框元素
function selDel( list )
 {
var len = list.options.length;
var idx = 0;
while ( idx< len ){
if ( list.options[idx].selected ){
list.options.remove(idx);
len = list.options.length;
         }
else{
idx ++;
         }
     }
 }
//描述: 检测列表框元素重复
function chkDup( item, list )
 {
for ( i=0; i<list.options.length; i++ ){
//alert( item + " - " + list.options[i].value );
if ( item == list.options[i].value ){
return true;
         }
     }                    
return false;
 }
//描述: 选择列表框的全部成员
function selSel( list, item )
 {
item.value = " ";
for ( i=0; i<list.options.length; i++ ){
list.options[i].selected=true;
item.value += list.options[i].value + " ";
     }
 }
function selSelSingle( list, value )
 {
for ( i=0; i<list.options.length; i++ ){
if ( list.options[i].value == value ){
list.options[i].selected=true;
break;
         }
     }
 }
//描述: 根据数组初始化列表框
function selList( item, arr )
 {
var curIndex, insIndex, val, text;
var arrItem = new Array();
if ( item ){
item.length = 0;
curIndex = 0;
for ( i=0; i<arr.length; i++ ){
item.length ++;
insIndex = item.length - 1;
if ( arr[i] ){
arrItem = arr[i].split( ", " );
text = arrItem[1];
val = arrItem[0];
item.options[ insIndex ].text = text;
item.options[ insIndex ].value= val;
            }
        }
    }
} 
</script>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章