javascript - 从javascript中的下拉列表列表中删除下拉列表
问题描述
我从我修改的 geeksforgeeks 获得了这段代码。原始代码将从文本区域列表中添加和删除。我试图对下拉列表做同样的事情。但是,它没有按预期工作。我想做的改变是:
- 按下“添加项目”按钮后,下拉列表应添加到前一个列表下方。
- 单击“删除项目”按钮时,应删除最底部的下拉列表。
这是我当前代码的链接: 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>
推荐阅读
- python - pythonanywhere 上使用 Telethon 的 Telegram 客户端
- html - 带有溢出的相对父级的粘性标题
- javascript - 在javascript中拆分点或逗号
- javascript - 如何从文本中删除空格、标点和符号
- python - JIRA-Python 的基本身份验证不再适用于 REST API 调用。接下来是什么?
- java - 如何在 for 循环(数组)中的 if 语句中打印
- android - 使用 AndroidX 概述的 TextField
- java - 测试:MySQL和H2不兼容
- ios - 在 NativeScript 5.4 插件中使用静态 iOS 库
- symfony4 - symfony 4:表单提交后如何处理后退箭头