码迷,mamicode.com
首页 > Web开发 > 详细

用jQuery封装的一些方法

时间:2017-06-26 20:08:43      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:color   val   type   eof   检测   数组   else   typeof   2.0   

先引入jQuery  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

  //序列化表单方法
    $.fn.serializeObject = function() {
        var res = {};
        var arr = this.serializeArray();
        $.each(arr, function() {
            if(res[this.name] !== undefined) {
                if(!res[this.name].push) {
                    res[this.name] = [res[this.name]];
                }
                res[this.name].push(this.value || ‘‘);
            } else {
                res[this.name] = this.value || ‘‘;
            }
        });
        //序列化时,如果radio、checkbox未被选中的话就不会出现,这里实现序列化时把radio、CheckBox未被选中时也添加进去
        var $radio = $(input[type=radio],input[type=checkbox], this);
        $.each($radio, function() {
            if(!res.hasOwnProperty(this.name)) {
                res[this.name] = ‘‘;
            }
        });
        return res;
    }

在一些常规的项目中,时常会用到地址栏传值,封装了一个获取地址栏内容并转换为json的方法

//获取地址栏内容并转换成json格式
    $.fn.getUrlJson = function() {
        var name, value; //定义变量用于存取地址栏的键值对
        var str = decodeURI(location.href); //取得整个地址栏
        var num = str.indexOf("?"); //获取?的所在位置
        str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

        var arr = str.split("&"); //根据&分割字符串,把各个参数放到数组里
        for(var i = 0; i < arr.length; i++) {
            num = arr[i].indexOf("="); //获取=的位置
            if(num > 0) {
                name = arr[i].substring(0, num);
                value = arr[i].substr(num + 1);
                this[name] = value;
            }
        }
    }

下面两个常用的方法

//计算表达式的值,与eval作用类似,eval不容易调试,性能差,好像安全性也有问题
    $.fn.evil = function(fn) {
        var Fn = Function; //一个变量指向Function,防止有些前端编译工具报错
        return new Fn(‘return ‘ + fn)();
    }
    //私有方法,检测参数是否合法
    $.fn.isValid = function(options) {
        return !options || (options && typeof options === "object") ? true : false;
    }

 

用jQuery封装的一些方法

标签:color   val   type   eof   检测   数组   else   typeof   2.0   

原文地址:http://www.cnblogs.com/htonline/p/7081867.html

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