我现在已经尝试过多次尝试这项工作而且我不知道该怎么做我使用了.selectedIndex方法等。但仍然没有运气,我已经制作了一系列我的标签,然后对它们进行排序,但我希望我的“请选择一个选项”作为默认选项。这是我的代码:)
function sorting()
{
var mylist = document.getElementById("dropdown");
arritems = new Array();
for(i=0; i<mylist.length; i++)
{
arritems[i] = mylist.options[i].text;
}
arritems.sort();
for(var i=0; i<mylist.length; i++)
{
mylist.options[i].text = arritems[i];
mylist.options[i].value = arritems[i];
}
}
这是我的HTML代码:
<form id="form"action = "#">
<label>First Name: </label> <input type="text" id="firstname" /> <br />
<label>Last Name: </label> <input type="text" id="lastname" /> <br />
Please select an option: <select id="dropdown">
<option id="please select" value="Please select an option" selected="selected">Please select an option</option>
<option id="boots" value="Boots" >Boots</option>
<option id="gloves" value="Gloves" >Gloves</option>
<option id="scarf" value="Scarf">Scarf</option>
<option id="hat" value="Hat">Hat</option>
<option id="glasses" value="Glasses">Glasses</option>
</select> <br />
<button id="submits" onclick="table();">Submit</button>
</form>
答案 0 :(得分:1)
尝试:
// get a handle to thedropdown
var select = document.getElementById('dropdown'), sorted;
if (select) {
// sort an array-copy of the options (exluding the first) by their text value
sorted = Array.prototype.slice.call(select.getElementsByTagName('option'), 1).sort(function (a, b) {
return a.innerText.localeCompare(b.innerText);
});
// flush 'sorted' while re-appending the dom-nodes
while(sorted.length > 0) {
select.appendChild(sorted.shift());
}
}