用jQuery封裝的一些方法


先引入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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM