首页 > 解决方案 > 从javascript中的下拉列表列表中删除下拉列表

问题描述

我从我修改的 geeksforgeeks 获得了这段代码。原始代码将从文本区域列表中添加和删除。我试图对下拉列表做同样的事情。但是,它没有按预期工作。我想做的改变是:

  1. 按下“添加项目”按钮后,下拉列表应添加到前一个列表下方。
  2. 单击“删除项目”按钮时,应删除最底部的下拉列表。

这是我当前代码的链接: https ://jsfiddle.net/coderr/dq12vL4j/

HTML

<ul id="list"></ul>
 
    <input type="text" id="candidate" />
    <button onclick="addItem()" class="buttonClass">
    Add item</button>
    <button onclick="removeItem()" class="buttonClass">
    Remove item</button>

Javascript

var myParent = document.body;

//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];

//Create and append select list
function addItem() {
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);

//Create and append the options
for (var i = 0; i < array.length; i++) {
    var option = document.createElement("option");
    option.value = array[i];
    option.text = array[i];
    selectList.appendChild(option);
}
}
        // Creating a function to remove item from list
        function removeItem() {

            // Declaring a variable to get select element
            var a = document.getElementById("list");
            var candidate = document.getElementById("candidate");
            var item = document.getElementById(candidate.value);
            a.removeChild(item);
        }

谢谢!

标签: javascripthtmldropdown

解决方案


更改了removeItem()函数,现在它删除了包含所有下拉列表的 div 的最后一个子项。还向display: block;div添加了一个

const list = document.getElementById('list')
var myParent = document.body

//Create array of options to be added
var array = ['Volvo', 'Saab', 'Mercades', 'Audi']

//Create and append select list
function addItem() {
  var selectList = document.createElement('select')
  selectList.id = 'mySelect'
  selectList.style.display = 'block'
  myParent.appendChild(selectList)

  //Create and append the options
  for (var i = 0; i < array.length; i++) {
    var option = document.createElement('option')
    option.value = array[i]
    option.text = array[i]
    selectList.appendChild(option)
  }
  list.appendChild(selectList)
}

// Creating a function to remove item from list
function removeItem() {
  list.lastChild?.remove()
}
<input type="text" id="candidate" />
<button onclick="addItem()" class="buttonClass">Add item</button>
<button onclick="removeItem()" class="buttonClass">Remove item</button>
<div id="list"></div>


推荐阅读