javascript - 单击按钮以创建 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>
解决方案
该示例使用单字母变量名称,如果他们使用了更有意义的变量名称(例如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,更好的文档和示例。
推荐阅读
- c++ - 如何在不知道其大小的情况下将输入输入到向量内的向量中?
- laravel - DataTable 在 Laravel 和 Vuejs 中被破坏
- postgresql - SERIAL 与 NULL 一起使用,始终作为 IDENTITY 生成而不是
- javascript - 单一 SPA 的替代方案
- git - Git忽略目录中的文件
- jquery - How to make Jquery datatable work on 'n' number of columns?
- aws-kms - 如何在 AWS KMS 中存储自定义密钥
- php - 如何修剪文本的右侧部分并显示结果
- excel - 在 iFrame 后面拉出单个 span id 值
- transformer - 如何使用 GPT2 模型获得立即下一个单词的概率?