Javascript 在列表框之间移动项目
我的页面上有两个列表框&我需要借助javascript在它们之间移动项目。 这是我的标记:Javascript 在列表框之间移动项目,javascript,asp.net,html,Javascript,Asp.net,Html,我的页面上有两个列表框&我需要借助javascript在它们之间移动项目。 这是我的标记: <asp:ListBox ID="ListBox1" Height="300px" runat="server" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox> <div> <asp:ImageButton ID="ButtonRight" runat="
<asp:ListBox ID="ListBox1" Height="300px" runat="server" AppendDataBoundItems="true"
SelectionMode="Multiple"></asp:ListBox>
<div>
<asp:ImageButton ID="ButtonRight" runat="server" ImageUrl="~/Images/right.gif" OnClientClick="return
LeftToRightMoveItems('AddSetup');" /><br />
<br />
<asp:ImageButton ID="ButtonLeft" runat="server" ImageUrl="~/Images/left.gif" OnClientClick="return
RightToLeftMoveItems('AddSetup');" />
</div>
<asp:ListBox ID="ListBox2" Height="300px" runat="server" AppendDataBoundItems="true"
SelectionMode="Multiple"></asp:ListBox>
该函数不接受状态参数。修改函数的签名以接受
状态
作为参数
function LeftToRightMoveItems(status) {
...
}
一旦提供了状态,代码也有一些问题。主要出现的情况是,varFromBox
被用作选择,而实际上它表示一个选项数组
例如,varFromBox
最初声明为对象数组:
var varFromBox = document.getElementById("<%=ListBox1.ClientID%>").options;
以下是我对这些问题的否定。我删除了try/catch,因此任何错误都更加明显。另请检查此示例:
函数LeftToRightMoveItems(状态){
如果(状态==“添加设置”){
var varFromBox=document.getElementById(“ListBox1”).options;
var varToBox=document.getElementById(“ListBox2”);
}
警报(varFromBox.length);
警报(varToBox.length);
if((varFromBox!=null)){
if(varFromBox.length<1){
警报('没有要移动的项目!');
返回false;
}
console.log(varFromBox.selectedIndex);
如果(varFromBox.selectedIndex==-1)//未选择任何项目时,索引将为-1
{
警报('请选择要移动的项目!');
返回false;
}
对于(var i=0;i
您可以从浏览器发布html源代码吗?如果您可以在页面加载后从浏览器发布html源代码,这将有助于调试此问题。已更新问题。请看一看。我想我发现了这个问题,再尝试一下。我发现了更多的问题,并提供了一个工作示例。
function LeftToRightMoveItems(status) {
...
}
var varFromBox = document.getElementById("<%=ListBox1.ClientID%>").options;
while (varFromBox.options.selectedIndex >= 0) {..}
function LeftToRightMoveItems(status){
if (status == "AddSetup") {
var varFromBox = document.getElementById("ListBox1").options;
var varToBox = document.getElementById("ListBox2");
}
alert(varFromBox.length);
alert(varToBox.length);
if ((varFromBox != null)) {
if (varFromBox.length < 1) {
alert('There are no items to move!');
return false;
}
console.log(varFromBox.selectedIndex);
if (varFromBox.selectedIndex == -1) // when no Item is selected the index will be -1
{
alert('Please select an item to move!');
return false;
}
for (var i = 0; i < varFromBox.length; i++) {
if (varFromBox[i].selectedIndex != -1) {
var newOption = new Option(); // Create a new instance of ListItem
newOption.text = varFromBox[i].text;
newOption.value = varFromBox[i].value;
varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox
document.getElementById("ListBox1").remove(varFromBox[i]); //Remove the item from Source Listbox
}
}
return false;
}
}