Internet Explorer 5.5Internet Explorer 7Internet Explorer 6.0IEVisual Studio .NET 2002.NET 1.0Visual Studio .NET 2003Windows 2003WebForms.NET 1.1.NET 3.0Visual Studio 2005Windows 2000Windows XP.NET 2.0IntermediateDevVisual StudioJavascriptWindows.NETASP.NET
将项目从一个列表框移动到另一个列表框。






3.48/5 (13投票s)
2007年5月12日

131890
本文解释了如何移动项目在两个列表框之间。
引言
这篇文章用于在 2 个列表框、组合框或下拉列表中移动列表项,如果列表框中没有选定的项目,它还会显示警报消息。
背景
这段代码可以在任何 Web 应用程序中使用,在 javascript 部分。
使用代码
假设
按钮的名称假定为 btnMoveRight 和 btnMoveLeft
列表框的名称假定为 ListBox1 和 ListBox2
Code for the javascript function: function fnMoveItems(lstbxFrom,lstbxTo) { var varFromBox = document.all(lstbxFrom); var varToBox = document.all(lstbxTo); if ((varFromBox != null) && (varToBox != null)) { if(varFromBox.length < 1) { alert('There are no items in the source ListBox'); return false; } if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1 { alert('Please select an Item to move'); return false; } while ( varFromBox.options.selectedIndex >= 0 ) { var newOption = new Option(); // Create a new instance of ListItem newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text; newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value; varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox varFromBox.remove(varFromBox.options.selectedIndex); //Remove the item from Source Listbox } } return false; } code for calling the javascript function: There are 2 methods of calling the javascript code, they are as under. 1. Add this code in the pageload btnMoveRight.Attributes.Add("onclick","return fnMoveItems('ListBox1','ListBox2')"); btnMoveLeft.Attributes.Add("onclick","return fnMoveItems('ListBox2','ListBox1')"); 2. Add this code in the HTML <input type = "button" id = "btnMoveRight" onclick = "fnMoveItems('ListBox1','ListBox2')"> <input type = "button" id = "btnMoveLeft" onclick = "fnMoveItems('ListBox2','ListBox1'">
关注点
如果您有任何疑问,请告诉我。
历史
即将添加关于 AJAX 的新文章。:-)