码迷,mamicode.com
首页 > 编程语言 > 详细

JQuery Option 排序

时间:2014-12-10 19:28:22      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:des   blog   io   ar   os   sp   java   on   div   

<script type="text/javascript">
        $(document).ready(function () {
            $("select").each(function (key, val) {
                SortOption($(this));
            });
        });

        function SortOption(slc)
        {
            var i = 0;
            var ops = "";
            var outdata = [];
            slc.find("option").each(function (key, val) {
                outdata[i] = {
                    ID: parseInt($(val).val()),
                    Option: $(val)[0].outerHTML
                };
                i++;
            });

            var jdata = 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 排序

标签:des   blog   io   ar   os   sp   java   on   div   

原文地址:http://www.cnblogs.com/windy2008/p/4155982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!