前两天要写一个操作select的东西,因为急着交货,随便写了一个操作LISTBOX的东西交上去了,
所有事件都是写在服务器端,觉得不是很好,今天重写了一个,是服务器端和客户端交互的
前端只有一个数据绑定:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SelectBind();
}
}
protected void SelectBind()
{
for (int i = 0; i < 20; i++)
selectleft.Items.Add(new ListItem("Andy"+(i+1).ToString(),(i+1).ToString()));
}
源:
<body>
<script type="text/javascript" language="javascript">
//交换全部,参数为要交换的对象
function TranAllOption(Obj1,Obj2)
{
if(Obj1.options.length <=0)
{ alert("没有要移动的项!"); return;}
while(Obj1.options.length >0)
{
Obj2.options.add(new Option(Obj1.options[0].text,Obj1.options[0].value));
Obj1.remove(0);
}
}
//交换部份,参数为要交换的对象
function TranOption(Obj1,Obj2)
{
var show = true;
for(var i=0;i<Obj1.options.length;i++)
{
if(Obj1.options[i].selected == true)
{
Obj2.options.add(new Option(Obj1.options[i].text,Obj1.options[i].value));
Obj1.remove(i);
i=i-1;
show = false;
}
}
if(show)
{
alert("请选择要移动的项!");
}
}
//上下移动
function SwapOption(obj,index)
{
if(obj.selectedIndex < 0)
{
alert("请选择要移动的项!");
return;
}
if(index == -1)
{
if (obj.selectedIndex == 0)
{
alert("已经移动到顶了!");
return;
}
else { obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex-1)); return;}
}
else if(index == 1)
{
if (obj.selectedIndex == obj.options.length-1)
{
alert("已经移动到底了!"); return;
}
else { obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex+1)); return; }
}
}
</script>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<table>
<tr><td rowspan="4"><select runat="server" multiple="true" id="selectleft" style="border-style:solid; width:200px; height:300px;" ></select></td>
<td><input id="Button1" type="button" value=">> 全部" οnclick="TranAllOption(selectleft,selectright)" /></td>
<td rowspan="4"><select runat="server" multiple="true" id="selectright" style="border-style:solid; width:200px; height:300px;" ></select></td>
<td rowspan="2"><input id="Button5" type="button" value="上移" οnclick="SwapOption(selectright,-1);" /></td></tr>
<tr><td><input id="Button2" type="button" value="> 增加" οnclick="TranOption(selectleft,selectright)" /></td></tr>
<tr><td><input id="Button3" type="button" value="<< 全部" οnclick="TranAllOption(selectright,selectleft)" /></td>
<td rowspan="2"><input id="Button6" type="button" value="下移" οnclick="SwapOption(selectright,1)" /></td></tr>
<tr><td><input id="Button4" type="button" value="< 增加" οnclick="TranOption(selectright,selectleft)" /></td></tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>