2012-01-11 55 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