现在的位置: 首页 > 综合 > 正文

【原】js实现2个listbox的乾坤大挪移

2012年12月01日 ⁄ 综合 ⁄ 共 2358字 ⁄ 字号 评论关闭
参考网上的代码,作了些修改,操作更简单。话不多説,看代码:(此方法同样适用于select,毕竟listBox在客户端就时一个select)

<script language="javascript" type="text/javascript">
        
        function AddAll(lsbSource,ltbDestination)
        
{
            var lst1
=window.document.getElementById(lsbSource);            
            var length 
= lst1.options.length;
             
if(length<=0)
                
return;
            var opNum
=0;
            var lst2
=window.document.getElementById(ltbDestination);
            
for(var i=length;i>0;i--)
            
{                  
                var v 
= lst1.options[i-1].value;
                var t 
= lst1.options[i-1].text; 
                lst2.options[opNum]
= new Option(t,v,true,true);
                lst1.options[i
-1].parentNode.removeChild(lst1.options[i-1]);     
                opNum
++;            
            }
    
        }

        
        function AddOne(lsbSource,ltbDestination)
        
{
            var lst1
=window.document.getElementById(lsbSource);
            var lstindex
=lst1.selectedIndex;           
            
if(lstindex<0)
                
return;
        var v 
= lst1.options[lstindex].value;
            var t 
= lst1.options[lstindex].text;            
        var lst2
=window.document.getElementById(ltbDestination);
            var length 
= lst2.options.length;
            lst2.options[length] 
= new Option(t,v,true,true);
            lst1.options[lstindex].parentNode.removeChild(lst1.options[lstindex]);
        }

 
</script>

==================================

页面部分

注意:这种方式添加的Listitem是不能在服务器端获取值的,因为ListBox在客户端是解释成了Select来的,以上所有操作都不能保存在页面的ViewState中。如果要取得ListBox中新增加的值,我的做法是在页面提交时,用js取出ListBox中的值,然后保存在一个隐藏域里来解决这个问题的。如果你有更好的方法,欢迎留下学习~~

抱歉!评论已关闭.