繁体   English   中英

JavaScript排序SELECT元素

[英]Javascript Sort SELECT Elements

有没有一种简单的方法可以对Javascript中的HTML Select元素列表进行排序? 我想要按他们的名字排序。 每个Select元素都有其他字段,例如标题和值。 我必须使用数组吗?

您应该使用数组的原因:

  • NodeList是只读的(您不能对其进行数组排序)
  • 与DOM操作相比,数组操作超级快

因此,您基本上需要将选项转换为数组,然后使用自定义比较功能对其应用sort函数。 最后,您以正确的顺序附加了元素。

用法

sortSelect("selection_id");

代码[ 实际操作中 ]

(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+

我会使用数组:

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

所有错误的解决方案..由于错误的索引或错误的字符处理。

工作解决方案。 在需要的地方添加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;
        }
    }
}

PS我评论说,这是因为搜索选项排序的搜索索引很高,并且所有答案解决方案都存在漏洞。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM