Javascript排序SELECT元素

时间:2010-07-13 19:05:14

标签: javascript html sorting

是否有一种简单的方法可以在Javascript中对HTML Select元素列表进行排序?我希望它按名字排序。每个Select元素都有其他字段,如title和value。我必须使用数组吗?

4 个答案:

答案 0 :(得分:2)

您应该使用数组的原因:

  • NodeLists是只读的(您不能对它们应用数组排序)
  • 与DOM操作相比,数组操作非常快

所以你基本上需要将选项转换为数组,然后使用自定义比较函数将sort函数应用于它。最后,按正确顺序追加元素。

<强>用法

sortSelect("selection_id");

代码[See it in action]

(function(window){

// array functions are not working
// on nodeLists on IE, we need to
// to convert them to array
function toArray( obj ) {
  var i, arr = [];
  for ( i = obj.length; i--; ){
    arr[i] = obj[i];
  }
  return arr;
}

// custom compare function for sorting
// by the option's value
function sortByName( a, b ) {
  if ( a.value < b.value ) return -1;
  else if( a.value > b.value ) return 1;
  else return 0;
}

window.sortSelect = function(id) {

  // select the elements to be ordered
  var sel   = document.getElementById(id),
      items = sel.getElementsByTagName("option"),
      len   = items.length;

  // convert to array, to make sorting possible
  items = toArray( items );

  // do the item sorting by their value
  items = items.sort( sortByName );

  // append them back to the parent in order
  for ( var i = 0; i < len; i++ ) {
    sel.appendChild( items[i] );
  }
};

})(this);​

经过测试:IE5.5 +,FF2 +,Chrome,Opera 9.6 +

答案 1 :(得分:1)

我会使用数组:

var x = [];
var select = document.getElementById('mySelect');
var length = select.options.length;
for(var i=length-1; i>=0; --i) {
   x.push(select.options[i]);
   select.removeChild(select.options[i]);
}
x.sort(function(o1,o2){
   if(o1.value > o2.value) {
      return 1;
   } else if(o1.value < o2.value) {
      return -1;
   }
   return 0;
});
for(var i=0; i<length; ++i) {
   select.appendChild(x[i]);
}

答案 2 :(得分:0)

所有有缺陷的解决方案......要么是因为索引不好,要么处理不好......

工作解决方案。在需要的地方添加unicode。真冒泡排序

//tjcoder
function sortlist(cl){
    var chars = "0123456789abcdefghijklmnopqrstuvwxyz";
    for(var i=0;i<cl.length-1;i++){
        if(chars.indexOf(cl.options[i].text.substr(0,1).toLowerCase())>chars.indexOf(cl.options[i+1].text.substr(0,1).toLowerCase())){
            var tmp=cl.options[i].text;
            cl.options[i].text=cl.options[i+1].text;
            cl.options[i+1].text=tmp;
            i=-1;
        }
    }
}

P.S。我评论说因为搜索选项排序的搜索索引很高,并且所有答案解决方案都被窃听。

答案 3 :(得分:0)

<script type="text/javascript">
function Sort1()
{
var x1 = document.getElementById('s1');
var x2= new Array();
for(i=0;i<x1.length;i++)
{
 x2.push(x1[i].value);  
}

x2.sort();
x1.length=0;

for(i=0;i<x2.length;i++)
{
document.f1.s1[i]=new Option(x2[i],x2[i]);
}
}
</script>
<body>
<select id="s1" name="s1">
<option value="Sachin">Sachin</option>
<option value="Sehwag">Sehwag</option>
<option value="Zahir">Zahir</option>
<option value="Dhoni">Dhoni</option>

</select><br />
<input type="button" value="Sort" onclick="Sort1()" /><br />
</form>
</body>