我有一个包含多个选项的下拉列表,现在我想在列表顶部插入一个新选项。我该怎么做?
function insertOptionAll (DOMtarget)
{
var option = document.createElement("option");
option.text = "Some option";
option.value = 0;
option.title = "Some option";
DOMtarget.add(option); //appends to the end
//DOMtarget.options[DOMtarget.options.length - 1].index = 0; --> doesnt work
}
答案 0 :(得分:1)
尝试......
DOMtarget.insertBefore(option, DOMtarget.options[0]);
请参阅:Add new <option> to all dropdown <select> tags using javascript
答案 1 :(得分:0)
function insertOption(selectId) {
var selectList = document.getElementById(selectId);
var option = document.createElement("option");
option.text = "Some option";
option.value = 0;
option.title = "Some option";
selectList.insertBefore(option, selectList.options[0]);
}