尝试将一个选项移动到另一个选择列表 [英] Trying to move one option to another select list

查看:76
本文介绍了尝试将一个选项移动到另一个选择列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过搜索这个并且所有的答案都在我的脑海之上,而且只是令我感到困惑和沮丧......我想要做的就是从左侧列表中选择一个选项,转到单击按钮时的右侧列表。这是我试图使用的脚本,它不适用于我...

I've tried searching this and all the answers are way above my head, and are just confusing and frustrating me... All I'm trying to do is make an option from the left list that is selected, move to the right list when I click a button. This is the script I'm attempting to use, and it isn't working for me...

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 {
  var selText = document.forms[0].leftList[selItem].text;
  var selValue = document.forms[0].leftList[selItem].value;
  var nextItem = document.forms[0].rightList.length;

  document.forms[0].rightList[nextItem].text = selText;
  document.forms[0].rightList[nextItem].value = selValue;
 }
}

关于如何在不超过以下情况下完成这项工作的任何想法使问题复杂化?

Any thoughts on how to make this work without over-complicating the matter?

推荐答案

您的代码中存在三个问题:

There were three problems in your code:


  1. 使用 document.getElementById 而不是 document.forms [0] .leftList

  2. 使用 cloneNode removeChild appendChild 移动元素

  3. 我没有看到你调用函数的任何地方 moveRight 。必须添加 onchange 事件

  1. Use document.getElementById instead of document.forms[0].leftList
  2. Use cloneNode and removeChild and appendChild to move your elements around
  3. I didn't see any place you were calling your function moveRight. Had to add an onchange event

示例代码:

function moveRight() {
    var leftlist = document.getElementById("leftList");
    var selItem = leftlist.selectedIndex;

    if (selItem == -1) {
        window.alert("You must first select an item on the left side.")
    } else {
        var rightlist = document.getElementById("rightList");
        var newOption = leftlist[selItem].cloneNode(true);

        leftlist.removeChild(leftlist[selItem]);
        rightlist.appendChild(newOption);
    }
}

document.getElementById('leftList').onchange = moveRight;

这篇关于尝试将一个选项移动到另一个选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆