首页 > 代码库 > JQuery Option 排序

JQuery Option 排序

<script type="text/javascript">        $(document).ready(function () {            $("select").each(function (key, val) {                SortOption($(this));            });        });        function SortOption(slc)        {            var i = 0;            var ops = "";            var outdata = http://www.mamicode.com/[];"option").each(function (key, val) {                outdata[i] = {                    ID: parseInt($(val).val()),                    Option: $(val)[0].outerHTML                };                i++;            });            var jdata = http://www.mamicode.com/outdata.sortObjectWith("ID", "asc", "fix");            $.each(jdata, function (key, item) {                ops += item.Option;            });            slc.html("");            slc.html(ops);        }        Array.prototype.sortObjectWith = function (key, t, fix) {            if (!this.length) { return this; }            t = t === ‘desc‘ ? ‘desc‘ : ‘asc‘;            fix = Object.prototype.toString.apply(fix) === ‘[object Function]‘ ? fix : function (key) { return key; };            switch (Object.prototype.toString.apply(fix.call({}, this[0][key]))) {                case ‘[object Number]‘:                    return this.sort(function (a, b) { return t === ‘asc‘ ? (fix.call({}, a[key]) - fix.call({}, b[key])) : (fix.call({}, b[key]) - fix.call({}, a[key])); });                case ‘[object String]‘:                    return this.sort(function (a, b) { return t === ‘asc‘ ? fix.call({}, a[key]).localeCompare(fix.call({}, b[key])) : fix.call({}, b[key]).localeCompare(fix.call({}, a[key])); });                default: return this;            }        }    </script>

 

JQuery Option 排序