如何进行默认设置<;选项>;在Javascript中按顺序排序?
我已经尝试过很多次了,但我不知道该怎么做,我使用了.selectedIndex方法等。但仍然没有运气,我已经做了一个数组,我的标签,然后排序他们,但我想我的“请选择一个选项”是默认选项。这是我的代码:)如何进行默认设置<;选项>;在Javascript中按顺序排序?,javascript,drop-down-menu,Javascript,Drop Down Menu,我已经尝试过很多次了,但我不知道该怎么做,我使用了.selectedIndex方法等。但仍然没有运气,我已经做了一个数组,我的标签,然后排序他们,但我想我的“请选择一个选项”是默认选项。这是我的代码:) 函数排序() { var mylist=document.getElementById(“下拉列表”); arritems=新数组(); 对于(i=0;i尝试: 试试: 谢谢这段代码为我带来了好处,我从未想过使用DOM或使用slice方法来选择数组的一部分:)非常感谢。非常感谢这段代码为我带来了
函数排序()
{
var mylist=document.getElementById(“下拉列表”);
arritems=新数组();
对于(i=0;i尝试:
试试:
谢谢这段代码为我带来了好处,我从未想过使用DOM或使用slice方法来选择数组的一部分:)非常感谢。非常感谢这段代码为我带来了好处,我从未想过使用DOM或使用slice方法来选择数组的一部分:)非常感谢。
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];
}
}
<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>
// 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());
}
}