2012-01-11 22 views
1

我已经尝试做这项工作,并且我不知道该怎么做我已经使用了.selectedIndex方法等多种尝试。但仍然没有运气,我已经制作了一系列我的标签,然后对其进行排序,但我希望我的“请选择一个选项”作为默认选项。这里是我的代码:)如何在按顺序排序时在JavaScript中创建默认<option>?

  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> 

回答

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

http://jsfiddle.net/dJqLL/

+0

感谢这段代码工作一种享受对我来说,我从来没有想过使用DOM或使用slice方法选择数组的一部分:)非常感谢。欢迎使用 – user1142894 2012-01-11 15:55:24

+0

@ user1142894;) – Yoshi 2012-01-11 16:35:43