代码改变世界

ASP.NET DEMO 12 : CheckBoxList 实现单选

2007-07-18 23:48  晓风残月  阅读(5503)  评论(8编辑  收藏  举报

一看标题估计大家都开始怀疑了:单选?为什么不直接使用 RadioButtonList ?
是的。你是对的。然而,实际应用中需求千变万化,谁让我们的客户够 BT 呢?

主要代码

只有一个通用的 CheckBoxList_Click 函数,
需要注意的是 CheckBoxList 可以呈现为 table 布局,也可以呈现为流布局(使用 span 做外部容器)

我的习惯是,脚本代码中,尽量不直接引用 html id,因为对于服务器控件对应的是 ClientID,而ClientID与控件层次关联的,不利于代码移植复用,因此尽可能选择直接传递对象,通过 DOM 获取相关的父控件和子控件。

function CheckBoxList_Click(sender) 
    
{
        
var container = sender.parentNode;        
        
if(container.tagName.toUpperCase() == "TD"// 服务器控件设置呈现为 table 布局(默认设置),否则使用流布局
            container = container.parentNode.parentNode; // 层次: <table><tr><td><input />
        }
        
        
var chkList = container.getElementsByTagName("input");
        
var senderState = sender.checked;
        
for(var i=0; i<chkList.length;i++{
            chkList[i].checked 
= false;
        }
     
        sender.checked 
= senderState;          
    }

<h3>单选效果的 CheckBoxList</h3>
    
<div style="float:left">
    
<h4>静态项</h4>
        
<asp:CheckBoxList ID="CheckBoxList1" BorderWidth="1" runat="server" RepeatLayout="Flow">
        
<asp:ListItem onclick="CheckBoxList_Click(this)" Value="Item1">Item1</asp:ListItem>
        
<asp:ListItem onclick="CheckBoxList_Click(this)" Value="Item2">Item2</asp:ListItem>
        
<asp:ListItem onclick="CheckBoxList_Click(this)" Value="Item3">Item3</asp:ListItem>
        
<asp:ListItem onclick="CheckBoxList_Click(this)" Value="Item4">Item4</asp:ListItem>
        
<asp:ListItem onclick="CheckBoxList_Click(this)" Value="Item5">Item5</asp:ListItem>
        
</asp:CheckBoxList>
    
</div>
    
<div style="float:left;padding-left:100px">
    
<h4>绑定项</h4>
        
<asp:CheckBoxList ID="CheckBoxList2" BorderWidth="1" runat="server" DataTextField="Value" DataValueField="Key" OnDataBound="CheckBoxList2_DataBound">        
        
</asp:CheckBoxList>
    
</div>

兼容性
IE 6 SP6,  FF 2.0,  Opera 9.2 测试通过

页面效果



下载