Html 如何以编程方式添加下拉列表 (<select>)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17001961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:14:39  来源:igfitidea点击:

How to add Drop-Down list (<select>) programmatically?

javascripthtmldrop-down-menuhtml-select

提问by Christos Baziotis

I want to create a function in order to programmatically add some elements on a page.

我想创建一个函数,以便以编程方式在页面上添加一些元素。

Lets say I want to add a drop-down list with four options:

假设我想添加一个带有四个选项的下拉列表:

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

How can I do that?

我怎样才能做到这一点?

回答by tymeJV

This will work (pure JS, appending to a div of id myDiv):

这将起作用(纯 JS,附加到 id 的 div myDiv):

Demo: http://jsfiddle.net/4pwvg/

演示:http: //jsfiddle.net/4pwvg/

var myParent = document.body;

//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];

//Create and append select list
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);
}

回答by 7stud

var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';

var cars = [
  "volvo",
  "saab",
  "mercedes",
  "audi"
];

var options_str = "";

cars.forEach( function(car) {
  options_str += '<option value="' + car + '">' + car + '</option>';
});

sel.innerHTML = options_str;


window.onload = function() {
  document.body.appendChild(sel);
};

回答by iConnor

I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)

我很快就做了一个可以实现这一点的函数,它可能不是最好的方法,但它只是有效并且应该是跨浏览器的,还请知道我不是 JavaScript 专家,所以任何提示都很棒:)

Pure Javascript Create Element Solution

纯 Javascript 创建元素解决方案

function createElement(){
    var element  = document.createElement(arguments[0]),
        text     = arguments[1],
        attr     = arguments[2],
        append   = arguments[3],
        appendTo = arguments[4];

    for(var key = 0; key < Object.keys(attr).length ; key++){
        var name = Object.keys(attr)[key],
             value = attr[name],
             tempAttr = document.createAttribute(name);
             tempAttr.value = value;
        element.setAttributeNode(tempAttr)
    }

    if(append){
        for(var _key = 0; _key < append.length; _key++) {
            element.appendChild(append[_key]);
        }
    }

    if(text) element.appendChild(document.createTextNode(text));

    if(appendTo){
        var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
        target.appendChild(element)
    }       

    return element;
}

lets see how we make this

让我们看看我们如何做到这一点

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

here's how it works

这是它的工作原理

    var options = [
        createElement('option', 'Volvo', {value: 'volvo'}),
        createElement('option', 'Saab', {value: 'saab'}),
        createElement('option', 'Mercedes', {value: 'mercedes'}),
        createElement('option', 'Audi', {value: 'audi'})
    ];


    createElement('select', null, // 'select' = name of element to create, null = no text to insert
        {id: 'Select1', name: 'drop1'}, // Attributes to attach
        [options[0], options[1], options[2], options[3]], // append all 4 elements
        'body' // append final element to body - this also takes a element by id without the #
    );

this is the params

这是参数

createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');

This function would suit if you have to append many element, if there is any way to improve this answer please let me know.

如果您必须附加许多元素,此功能将适用,如果有任何方法可以改进此答案,请告诉我。

edit:

编辑:

Here is a working demo

这是一个工作演示

JSFiddle Demo

JSFiddle 演示

This can be highly customized to suit your project!

这可以高度定制以适合您的项目!

回答by user3385463

This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.

此代码将动态创建一个选择列表。首先,我创建一个包含汽车名称的数组。其次,我动态创建一个 select 元素并将其分配给变量“sEle”并将其附加到 html 文档的正文中。然后我使用 for 循环遍历数组。第三,我动态创建选项元素并将其分配给变量“oEle”。使用 if 语句,我将属性 'disabled' 和 'selected' 分配给第一个选项元素 [0],以便它始终被选中并被禁用。然后我创建一个文本节点数组“oTxt”来附加数组名称,然后将文本节点附加到选项元素,该元素稍后附加到选择元素。

var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];

var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);

for (var i = 0; i < array.length; ++i) {
  var oEle = document.createElement('option');

  if (i == 0) {
    oEle.setAttribute('disabled', 'disabled');
    oEle.setAttribute('selected', 'selected');
  } // end of if loop

  var oTxt = document.createTextNode(array[i]);
  oEle.appendChild(oTxt);

  document.getElementsByTagName('select')[0].appendChild(oEle);
} // end of for loop

回答by Kevin ?sterkilde

Here's an ES6 version of the answer provided by 7stud.

这是7stud提供的答案的 ES6 版本。

const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';

const cars = [
  "Volvo",
  "Saab",
  "Mercedes",
  "Audi",
];

const options = cars.map(car => {
  const value = car.toLowerCase();
  return `<option value="${value}">${car}</option>`;
});

sel.innerHTML = options;

window.onload = () => document.body.appendChild(sel);

回答by Aliaksandr Shpak

const countryResolver = (data = [{}]) => {
    const countrySelecter = document.createElement('select');
    countrySelecter.className = `custom-select`;
    countrySelecter.id = `countrySelect`;
    countrySelecter.setAttribute("aria-label", "Example select with button addon");

    let opt = document.createElement("option");
    opt.text = "Select language";
    opt.disabled = true;
    countrySelecter.add(opt, null);
    let i = 0;
    for (let item of data) {
        let opt = document.createElement("option");
        opt.value = item.Id;
        opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
        countrySelecter.add(opt, null);
    }
    return countrySelecter;
};

回答by chx

Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:

这是一个 ES6 版本,转换为 vanilla JS 应该不会太难,但我已经有了 jQuery:

function select(options, selected) {
  return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);
}
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

回答by Jesus Cuesta

const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];

let domSelect = document.createElement('select');
domSelect.multiple = true;
document.getElementsByTagName('body')[0].appendChild(domSelect);


for (const i in cars) {
  let optionSelect = document.createElement('option');

  let optText = document.createTextNode(cars[i]);
  optionSelect.appendChild(optText);

  document.getElementsByTagName('select')[0].appendChild(optionSelect);
}

回答by kanaan

it's very simple yet tricky but here is what you wanted, hope it's helpful : this function generates a select list from 1990 to 2018 i think this example can help ya, if you want to add any other value just change value of x and y ;)

它非常简单但很棘手,但这是您想要的,希望对您有所帮助: 此函数生成一个从 1990 年到 2018 年的选择列表,我认为此示例可以帮助您,如果您想添加任何其他值,只需更改 x 和 y 的值; )

function dropDown(){
    var start = 1990;
    var today = 2019;
    document.write("<select>");
    for (var i = start ; i <= today; i++)
    document.write("<option>" + i + "</option>");
}
document.write("</select>");

dropDown();