使用Javascript如何将选项附加到HTML选择菜单?
例如:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
答案 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)
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
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>
`)