附加选项以选择菜单?

时间:2011-03-03 15:27:09

标签: javascript html

使用Javascript如何将选项附加到HTML选择菜单?

例如:

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

http://jsfiddle.net/SSwhr/

4 个答案:

答案 0 :(得分:61)

这样的事情:

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);

答案 1 :(得分:15)

$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})

答案 2 :(得分:8)

HTML

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

的JavaScript

 var mySelect = document.getElementById('mySelect'),
    newOption = document.createElement('option');

newOption.value = 'bmw';

// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
    newOption.innerText = 'BMW';
}
else
{
    newOption.textContent = 'BMW';
}

mySelect.appendChild(newOption);

Demo →

答案 3 :(得分:1)

您还可以使用insertAdjacentHTML功能:

const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'

select.insertAdjacentHTML('beforeend', `
  <option value="${value}">${label}</option>
`)