在.net中用CheckBoxList实现单选

  在.net中提供了Radiobuttonlist来实现单选的,但是我一直喜欢用CheckBoxList 原因我觉得CheckBoxList 控件页面展示效果要好看一些,呵呵

  这里是先CheckBoxList 实现单选采用了控件的点击事件 调用js来控制单选的

  例如页面如下:

  

复制代码 代码如下:

  <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>

  这里是调用的js

  原理就是:

  1、获得页面控件集合,循环查找check

  2、设置check 为false ,再将传入的控件设置选中

  

复制代码 代码如下:

  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;

  }