将元素从列表移动到另一个列表并反向javascript

时间:2016-11-20 16:47:39

标签: javascript

我想从第二个列表中移动项目,反之亦然。首先工作。 我试着写第二个清单,但它没有用,我也不知道为什么。 有人能帮助我吗? 这是我试图做的。

   <html>
    <head>
      <script>
      function moveRight() {
    var selItem = document.forms[0].leftList.selectedIndex;
    if (selItem == -1) {
        window.alert("You must first select an item on the left side.")
    } else {
        document.forms[0].rightList.add(document.forms[0].leftList[selItem], null);
    }
}
function moveLeft(){
  var selItem=document.forms[1].leftRight.selectedIndex;
  if (selItem == -1) {
      window.alert("You must first select an item on the right side.")
  } else {
      document.forms[1].leftList.add(document.forms[1].rightList[selItem], null);
  }
}
</script>
    </head>
    <body>
      <form name="form1" onsubmit="return false;">
    <select name="leftList" multiple="multiple">
      <option value="item1">Item1</option>
      <option value="item2">Item2</option>
      <option value="item3">Item3</option>
      <option value="item4">Item4</option>
    </select>
    <select name="rightList" multiple="multiple">
      <option value="elem1" > Elem1</option>
      <option value="elem2">Elem2</option>
    </select>

    <button onclick="moveRight()">Move to the right</button>
    <button onclick="moveLeft()">Move to the left</button>
</form>
      </body>
    </html>

1 个答案:

答案 0 :(得分:2)

有两个问题

1:没有形式[1]元素,它应该只是表格[0]。

2:document.forms [1] .leftRight is elemnt它应该是document.forms [0] .rightList

function moveLeft(){
  var selItem=document.forms[0].rightList.selectedIndex;
  if (selItem == -1) {
      window.alert("You must first select an item on the right side.")
  } else {
      document.forms[0].leftList.add(document.forms[0].rightList[selItem], null);
  }
}

工作示例:https://plnkr.co/edit/uw28oLtQBjfW9vS0d5ld?p=preview