从 javascript 中的下拉列表列表中删除下拉列表

Delete dropdown list from list of dropdown lists in javascript

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

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

这是我当前代码的 link: 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);
        }

谢谢!

更改了 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>