使用 JavaScript 更改选项的位置
Change position of an option using JavaScript
我有一个包含多个选项的下拉列表,现在我想在列表顶部插入一个新选项。我该怎么做?
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
}
尝试...
DOMtarget.insertBefore(option, DOMtarget.options[0]);
参见:Add new <option> to all dropdown <select> tags using javascript
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]);
}
我有一个包含多个选项的下拉列表,现在我想在列表顶部插入一个新选项。我该怎么做?
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
}
尝试...
DOMtarget.insertBefore(option, DOMtarget.options[0]);
参见:Add new <option> to all dropdown <select> tags using javascript
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]);
}