如何在<option>按顺序排序时在 Javascript 中设置默认值?



我已经尝试了很多次,但我不知道该怎么办,我使用了.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>

尝试:

// 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());
  }
}

http://jsfiddle.net/dJqLL/

最新更新