asp.net中的ListBox控件添加双击事件

时间:2024-01-08 22:13:44

问题:在Aspx页里的ListBox A中添加双击事件,将选中项添加到另一个ListBox B中,双击ListBox B中的选中项,删除当前选中项

页面:

  <asp:ListBox ID="ListUsers" runat="server" Height="313px" SelectionMode="Multiple" Width="185px" ></asp:ListBox>

  <asp:ListBox ID="ListSelectedUsers" runat="server" Height="313px"  SelectionMode="Multiple" Width="199px" "></asp:ListBox>

  <asp:TextBox ID="SelectedMode" runat="server" Style="display: none"></asp:TextBox>

JS 脚本:

 function SelectOne() {

            var lst1 = window.document.getElementById("ListUsers");
var lstindex = lst1.selectedIndex;
if (lstindex < )
return;
var v = lst1.options[lstindex].value;
var t = lst1.options[lstindex].text;
var lst2 = window.document.getElementById("ListSelectedUsers");
var mode = window.document.getElementById("SelectedMode");
if (mode.value == "True") { //如果是单值,先删除所有
for (var i = lst2.options.length - ; i >= ; i--) {
lst2.remove(i);
}
lst2.add(new Option(t, v, true, true), );
} else{
var isExists = false;
for (var i = ; i < lst2.options.length; i++) {
if (lst2.options[i].value == v) { //防止添加重复项
isExists = true;
break;
}
}
if (!isExists) {
lst2.options[lst2.options.length] = new Option(t, v, true, true);
}
}
} //选择一条数据删除
function DelOne() {
var lst = window.document.getElementById("ListSelectedUsers");
var lstindex = lst.selectedIndex;
if (lstindex >= ) {
var v = lst.options[lstindex].value + ";";
lst.options[lstindex].parentNode.removeChild(lst.options[lstindex]);
}
}

后台代码:

if (!IsPostBack)
{
ListBoxBand();
SelectedMode.Text = "True";
ListUsers.Attributes.Add("onDblClick", "SelectOne()");//双击事件
ListSelectedUsers.Attributes.Add("onDblClick", "DelOne()");//双击事件
} private void ListBoxBand()
{ for (int i = ; i < ; i++)
{
   ListUsers.Items.Add(new ListItem("Index" + i, i.ToString()));
}
}

效果:

asp.net中的ListBox控件添加双击事件

参考来源:asp.net中的ListBox控件添加双击事件

js操作ListBox实现多项的添加和删除