在网页开发时,有时会用到下拉框控件,如果通过后台传入的数据没有做排序,而且数据相对较多,那么在前台页面使用下拉框将是件比较痛苦的事。
这时候有两种做法,一种是修改后台代码,增加相关的数据排序处理;另一种是在web前端进行处理,这样的好处时不用对工程打包发布,只需要替换相关的html文件。
下面介绍下web端处理的方式:
前端html为
<select name="data1" id="data1" style="width:200px;">
其中:data1位标签名称
增加前台JavaScript处理逻辑为
window.onload = function (){
var isDesc = true;
var select1= document.getElementById("data1"); //获取相关select
var ops = select1.getElementsByTagName("option"); //获取对应的option HTMLCollection
var arrOps = Array.prototype.slice.call(ops, 0); //转换为数据
arrOps.sort(function (a, b) {
if (a.text > b.text) {
return isDesc == true ? 1 : -1;
} else {
return isDesc == true ? -1 : 1;
}
});
select1.options.length = 0; //清除原有select数据
arrOps.map(function (op) {
select1.appendChild(op); //增加排序数据
});
}
对于select中存在中文信息时,需要适当调整相关的JavaScript脚本按照中文拼音排序,具体代码为
window.onload = function (){
var isDesc = true;
var select1= document.getElementById("data1"); //获取相关select
var ops = select1.getElementsByTagName("option"); //获取对应的option HTMLCollection
var arrOps = Array.prototype.slice.call(ops, 0); //转换为数据
arrOps.sort(function (a, b) {
if (a.text.localeCompare(b.text, 'zh')>0) {
return isDesc == true ? 1 : -1;
} else {
return isDesc == true ? -1 : 1;
}
});
select1.options.length = 0; //清除原有select数据
arrOps.map(function (op) {
select1.appendChild(op); //增加排序数据
});
}