gpt4 book ai didi

Javascript 对 SELECT 元素进行排序

转载 作者:行者123 更新时间:2023-11-30 23:45:15 25 4
gpt4 key购买 nike

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

最佳答案

应该使用数组的原因:

  • NodeList 是只读的(不能对其应用数组排序)
  • 与 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+

关于Javascript 对 SELECT 元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com