JavaScript:动态添加和删除选项

摘要:在本教程中,您将学习如何在 JavaScript 中动态向 select 元素 添加选项,以及如何从选择框中删除选项。

HTMLSelectElement 类型表示 <select> 元素。它具有 add() 方法,该方法可动态地向 <select> 元素添加选项,还具有 remove() 方法,该方法可从 <select> 元素中删除选项。

  • add(option,existingOption) – 在现有选项之前向 <select> 元素添加新的 <option> 元素。
  • remove(index) – 从 <select> 元素中删除由索引指定的选项。

添加选项

要动态地向 <select> 元素添加选项,请执行以下步骤。

  • 首先,创建一个新的选项。
  • 其次,将选项添加到选择框中。

在 JavaScript 中,有多种方法可以动态创建选项并将其添加到 <select> 元素中。

1)使用 Option 构造函数和 add() 方法

首先,使用 Option 构造函数创建具有指定选项文本和值的新的选项。

let newOption = new Option('Option Text','Option Value');Code language: JavaScript (javascript)

然后,调用 HTMLSelectElement 元素的 add() 方法。

const select = document.querySelector('select'); 
select.add(newOption,undefined);Code language: JavaScript (javascript)

add() 方法接受两个参数。第一个参数是新选项,第二个参数是现有选项。

在本例中,我们在第二个参数中传递 undefinedadd() 方法会将新选项添加到选项列表的末尾。

2)使用 DOM 方法

首先,使用 DOM 方法构造新的选项。

// create option using DOM
const newOption = document.createElement('option');
const optionText = document.createTextNode('Option Text');
// set option text
newOption.appendChild(optionText);
// and option value
newOption.setAttribute('value','Option Value');Code language: JavaScript (javascript)

其次,使用 appendChild() 方法将新选项添加到选择框中。

const select = document.querySelector('select'); 
select.appendChild(newOption);Code language: JavaScript (javascript)

删除选项

也有多种方法可以动态地从选择框中删除选项。

第一种方法是使用 HTMLSelectElement 类型的 remove() 方法。以下示例说明如何删除第一个选项。

select.remove(0); Code language: CSS (css)

第二种删除选项的方法是使用 options 集合通过索引引用选项,并将其值设置为 null

select.options[0] = null;Code language: JavaScript (javascript)

第三种方法是使用 removeChild() 方法并删除指定的选项。以下代码删除 selectBox 中的第一个元素。

// remove the first element:
select.removeChild(selectBox.options[0]);Code language: JavaScript (javascript)

要删除选择框中的所有选项,请使用以下代码。

function removeAll(selectBox) {
    while (selectBox.options.length > 0) {
        select.remove(0);
    }
}Code language: JavaScript (javascript)

当您删除第一个选项时,选择框会将另一个选项移动到第一个选项的位置。removeAll() 函数会重复删除选择框中的第一个选项,因此会删除所有选项。

将所有内容组合在一起

我们将构建一个 应用程序,允许用户从输入文本的值中添加新的选项,并删除一个或多个选定的选项。

这是项目的结构

├── css
|  └── style.css
├── js
|  └── app.js
└── index.html

index.html

<!DOCTYPE html>
<html>

    <head>
        <title>JavaScript Selected Value</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/style.css" rel="stylesheet">
    </head>
    <body>
        <div id="container">
            <form>
                <label for="framework">Framework:</label>
                <input type="text" id="framework" placeholder="Enter a framework" autocomplete="off">

                <button id="btnAdd">Add</button>

                <label for="list">Framework List:</label>
                <select id="list" name="list" multiple>

                </select>
                <button id="btnRemove">Remove Selected Framework</button>
            </form>
        </div>
        <script src="js/app.js"></script>
    </body>

</html>Code language: HTML, XML (xml)

js/app.js

const btnAdd = document.querySelector('#btnAdd');
const btnRemove = document.querySelector('#btnRemove');
const listbox = document.querySelector('#list');
const framework = document.querySelector('#framework');

btnAdd.onclick = (e) => {
  e.preventDefault();

  // validate the option
  if (framework.value == '') {
    alert('Please enter the name.');
    return;
  }
  // create a new option
  const option = new Option(framework.value, framework.value);
  // add it to the list
  listbox.add(option, undefined);

  // reset the value of the input
  framework.value = '';
  framework.focus();
};

// remove selected option
btnRemove.onclick = (e) => {
  e.preventDefault();

  // save the selected options
  let selected = [];

  for (let i = 0; i < listbox.options.length; i++) {
    selected[i] = listbox.options[i].selected;
  }

  // remove all selected option
  let index = listbox.options.length;
  while (index--) {
    if (selected[index]) {
      listbox.remove(index);
    }
  }
};
Code language: JavaScript (javascript)

样式可以 在这里找到

工作原理

首先,使用 querySelector() 方法选择元素,包括输入文本、按钮和选择框。

const btnAdd = document.querySelector('#btnAdd');
const btnRemove = document.querySelector('#btnRemove');
const listbox = document.querySelector('#list');
const framework = document.querySelector('#framework');Code language: JavaScript (javascript)

其次,将单击事件监听器附加到 btnAdd 按钮。

如果输入文本的值为空,我们会显示一个 警报,通知用户姓名是必需的。否则,我们将创建一个新的选项并将其添加到选择框中。添加选项后,我们将重置输入文本的输入文本,并将焦点设置到输入文本上。

btnAdd.addEventListener('click', (e) => {
  e.preventDefault();

  // validate the option
  if (framework.value.trim() === '') {
    alert('Please enter the name.');
    return;
  }
  // create a new option
  const option = new Option(framework.value, framework.value);

  // add it to the list
  listbox.add(option, undefined);

  // reset the value of the input
  framework.value = '';
  framework.focus();
});Code language: JavaScript (javascript)

第三,向 btnRemove 按钮注册单击事件监听器。在事件监听器中,我们将选定的选项保存在数组中,然后逐个删除它们。

btnRemove.addEventListener('click', (e) => {
  e.preventDefault();

  // save the selected options
  let selected = [];

  for (let i = 0; i < listbox.options.length; i++) {
    selected[i] = listbox.options[i].selected;
  }

  // remove all selected option
  let index = listbox.options.length;
  while (index--) {
    if (selected[index]) {
      listbox.remove(index);
    }
  }
});Code language: JavaScript (javascript)

摘要

  • JavaScript 使用 HTMLSelectElement 类型来表示 <select> 元素。
  • 使用 HTMLSelectElementadd() 方法向 <select> 元素添加选项。
  • 使用 HTMLSelectElementremove() 方法从 <select> 元素中删除选项。
本教程对您有帮助吗?