JavaScript对select标签文字内容进行排序

在网页开发时,有时会用到下拉框控件,如果通过后台传入的数据没有做排序,而且数据相对较多,那么在前台页面使用下拉框将是件比较痛苦的事。

这时候有两种做法,一种是修改后台代码,增加相关的数据排序处理;另一种是在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);                         //增加排序数据

            });
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mystonelxj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值