首页 > 解决方案 > 单击按钮以创建 SELECT 和 OPTION 元素

问题描述

我发布的代码示例来自https://www.w3schools.com/此特定代码在切换按钮后会产生一个选择选项。目前,该代码生成一个只有一个选项的选择下拉列表,但我想要多个选项。特别是,我有一个数组,我想将其填充为选择框中的选项。如何向下拉列表添加多个选项?谢谢!

<html>
<body>
  <p>Click the button to create a SELECT and an OPTION element.</p>
  <button onclick="myFunction()">Try it</button>

  <script>
    function myFunction() {
      var selectElement = document.createElement("SELECT");
      selectElement.setAttribute("id", "mySelect");
      document.body.appendChild(selectElement);

      var optionElement = document.createElement("option");
      optionElement.setAttribute("value", "volvocar");

      var textNode = document.createTextNode("Volvo");
      optionElement.appendChild(textNode);

      document.getElementById("mySelect").appendChild(optionsElement);
    }
  </script>
</body>
</html>

标签: javascripthtml

解决方案


该示例使用单字母变量名称,如果他们使用了更有意义的变量名称(例如newOption代替z),您可能已经解决了 - 只需重复生成新选项的那段代码,可能在循环内。

function createSelect() {
  var select = document.createElement("SELECT");
  select.setAttribute("id", "mySelect");
  document.body.appendChild(select);

  var items = ["Foo","Bar","Zoo"];
  for(var i = 0;i<items.length;i++) {
    var item = items[i];
    var newOption = document.createElement("option");
    newOption.setAttribute("value", item);
    var textNode = document.createTextNode(item);
    newOption.appendChild(textNode);
    select.appendChild(newOption);
  }
}
<p>Click the button to create a SELECT and an OPTION element.</p>

<button onclick="createSelect()">Try it</button>

忠告 - 使用mdn而不是 w3schools,更好的文档和示例。


推荐阅读