简体   繁体   English

如何使用JavaScript向选项标签添加选项?

[英]How to add options to a select tag with JavaScript?

I am attempting to create a bit of JavaScript that, on the click of a button, adds a tag filled with options. 我试图创建一些JavaScript,只需单击一个按钮,即可添加一个填充有选项的标签。 The options will be defined with an array called "roster". 这些选项将使用名为“名册”的数组进行定义。 What I would like to see is a dropdown that has options for sanchez, ronaldo, and ozil. 我想看到的是一个下拉菜单,其中包含桑切斯,罗纳尔多和厄齐尔的选项。

 var roster = [ "ozil", "sanchez", "ronaldo" ]; var reps = null; var dropdown = null; var scorerOption = "<option value='" + reps + "' class='scorerOption'>" + roster[reps] + "</option>"; function makeDropdown () { dropdown = "<select class='scorer'>" + String(scorerOption).repeat(roster.length) + "</select>"; document.getElementById("rawr").innerHTML = dropdown; } 
 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p id="rawr"><button onclick="makeDropdown()">Select a player</button></p> </body> </html> 

As you may notice, the and tags appear, but all have innerHTML's and values of "undefined". 您可能会注意到,和标记出现了,但是都具有innerHTML的和值为“ undefined”。 How can I change that so it displays the names sanchez, ronaldo, and ozil? 如何更改它以显示名称sanchez,ronaldo和ozil?

You'll need to loop through the array and for each element in the array, create and insert a new option . 您需要遍历数组,并为数组中的每个元素创建并插入一个新的option

You should also not use inline HTML event handling attributes ( onclick ), see here for why. 您也不应使用内联HTML事件处理属性( onclick ),请参阅此处了解原因。

Lastly, it's generally better to create dynamic elements with the DOM API call of document.createElement() , rather than build up strings of HTML as the strings can become difficult to manage and the DOM API provides a clean object-oriented way to configure your newly created elements. 最后,通常最好使用DOM API调用document.createElement()创建动态元素,而不是构建HTML字符串,因为字符串可能变得难以管理,并且DOM API提供了一种干净的面向对象的方式来配置您的新创建的元素。

 var roster = [ "ozil", "sanchez", "ronaldo" ]; // Work with your DOM elements in JavaScript, not HTML var btn = document.getElementById("btn"); btn.addEventListener("click", makeDropdown); function makeDropdown () { // Dynamically generate a new <select> element as an object in memory var list = document.createElement("select"); // Configure the CSS class for the element list.classList.add("scorer"); // Loop over each of the array elements roster.forEach(function(item){ // Dynamically create and configure an <option> for each var opt = document.createElement("option"); opt.classList.add("scorerOption"); opt.textContent = item; // Add the <option> to the <select> list.appendChild(opt); }); // Add the <select> to the document document.getElementById("rawr").appendChild(list); } 
 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p id="rawr"><button id="btn">Select a player</button></p> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM