適合自己的,才是最好用的,插件講究的是通用性和簡潔性,介紹幾款收集的比較好用的JQUERY插件,有自己寫的也有收集后改寫的,歡迎帶走。
插件一:$.request
說明:在WEB編程中,經常會碰到接收當前請求的參數並根據參數做處理的情況,這款插件就是返回當前請求的參數,如果沒有,返回空字符串。
代碼:
<script type="text/javascript"> $.extend({ request: function (paras) { var url = location.href; var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"); var paraObj = {} for (i = 0; j = paraString[i]; i++) { paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length); } var returnValue = paraObj[paras.toLowerCase()]; if (typeof (returnValue) == "undefined") { return ""; } else { return returnValue; } } }); </script>
用法:
$(function () { //當前URL:/index.html?para=111 document.write($.request("para")); //結果:111 })
插件二:$.format
說明:和.NET中的String. Format類似,將字符串中的數字格式替換為指定字符串,並返回替換后的結果。
代碼:
$.extend({ format: function (source, params) { if (arguments.length == 1) return function () { var args = $.makeArray(arguments); args.unshift(source); return $.format.apply(this, args); }; if (arguments.length > 2 && params.constructor != Array) { params = $.makeArray(arguments).slice(1); } if (params.constructor != Array) { params = [params]; } $.each(params, function (i, n) { source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); }); return source; } });
用法:
$(function () { var tem = "{0} is {1}"; document.write($.format(tem, "this", "format")); //結果this is format })
插件三:$.cookie
說明:讀取或者設置網站中的cookie,同時可以設置作用域和過期時間。這個插件用過的人應該比較多,我將它稍微簡化了一下。
代碼:
$.extend({ cookie: function (name, value, options) { if (typeof value != 'undefined') { options = options || {}; if (value === null) { value = ''; options = $.extend({}, options); options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } } });
用法:
$(function () { //寫,有效期為一天,作用域為整個網站 $.cookie("user", "123456", { expires: 1, path: '/' }); //讀 var name = $.cookie("user"); })
插件四:$.toJSON
說明:將對象轉換為JSON格式,轉換JSON一般常用於JQUERY AJAX中,因為QUERY AJAX要求請求的參數必須為JSON格式。
代碼:
(function ($) { 'use strict'; var escape = /["\\\x00-\x1f\x7f-\x9f]/g, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, hasOwn = Object.prototype.hasOwnProperty; $.toJSON = typeof JSON === 'object' && JSON.stringify ? JSON.stringify : function (o) { if (o === null) { return 'null'; } var pairs, k, name, val, type = $.type(o); if (type === 'undefined') { return undefined; } if (type === 'number' || type === 'boolean') { return String(o); } if (type === 'string') { return $.quoteString(o); } if (typeof o.toJSON === 'function') { return $.toJSON(o.toJSON()); } if (type === 'date') { var month = o.getUTCMonth() + 1, day = o.getUTCDate(), year = o.getUTCFullYear(), hours = o.getUTCHours(), minutes = o.getUTCMinutes(), seconds = o.getUTCSeconds(), milli = o.getUTCMilliseconds(); if (month < 10) { month = '0' + month; } if (day < 10) { day = '0' + day; } if (hours < 10) { hours = '0' + hours; } if (minutes < 10) { minutes = '0' + minutes; } if (seconds < 10) { seconds = '0' + seconds; } if (milli < 100) { milli = '0' + milli; } if (milli < 10) { milli = '0' + milli; } return '"' + year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"'; } pairs = []; if ($.isArray(o)) { for (k = 0; k < o.length; k++) { pairs.push($.toJSON(o[k]) || 'null'); } return '[' + pairs.join(',') + ']'; } if (typeof o === 'object') { for (k in o) { if (hasOwn.call(o, k)) { type = typeof k; if (type === 'number') { name = '"' + k + '"'; } else if (type === 'string') { name = $.quoteString(k); } else { continue; } type = typeof o[k]; if (type !== 'function' && type !== 'undefined') { val = $.toJSON(o[k]); pairs.push(name + ':' + val); } } } return '{' + pairs.join(',') + '}'; } }; $.quoteString = function (str) { if (str.match(escape)) { return '"' + str.replace(escape, function (a) { var c = meta[a]; if (typeof c === 'string') { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + str + '"'; }; }(jQuery));
用法:
$(function () { var obj = { name: "jack", age:18 } $.ajax({ type: "POST", url: "/ajax.aspx/Method", data: $.toJSON(obj), contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { //success }, error: function (result) { //error } }); })
插件五:$.myAjax
說明:由於之前的項目中經常要用到Jquery Ajax,無可避免的就要重復的復制黏貼Jquery Ajax的那一大堆參數。這個插件是我圖省事,算是對JQUERY AJAX進行了再一次封裝,支持最基本的事件回發。
代碼:
$.extend({ myAjax: function (url, data, callback) { $.ajax({ type: "POST", url: url, data: data == null ? "{}" : $.toJSON(data), contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { callback(result.d) }, error: function (result) { } }); } });
用法:
$(function () { var obj = { name: "jack", age:18 } $.myAjax("/ajax.aspx/Method", obj, function (data) { alert(data); }) })
關於Jqeury的擴展方法$.extend不懂的同學可以搜一下,上面的擴展方法也可以集中到一個extend中,如:
$.extend({ request: function (paras) { .. }, format: function (source, params) { .. }, cookie: function (name, value, options) { .. }, myAjax: function (url, data, callback) { .. } })
其他方法:
1.驗證郵箱和手機
代碼:
function CheckEmail(email) { Return /^[\w\.\-\+]+@([\w\-]+\.)+[a-z]{2,4}$/ig.test(email) } alert(CheckEmail(123456@163.com)); function CheckPhone(phone) { Return /^1[3|4|5|8][0-9]\d{8}$/.test(phone) } alert(CheckPhone(13333333333));
2.字符串方法擴展
// 清除兩邊的空格 String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ''); }; var s1=" 123 "; alert(s1.trim()); //結果為123 // 合並多個空白為一個空白 String.prototype.ResetBlank = function () { var regEx = /\s+/g; return this.replace(regEx, ' '); }; var s2=" 1 3"; alert(s2.ResetBlank ()); //結果為1 3 // 保留數字 String.prototype.GetNum = function () { var regEx = /[^\d]/g; return this.replace(regEx, ''); }; // 保留中文 String.prototype.GetCN = function () { var regEx = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g; return this.replace(regEx, ''); }; // String轉化為Number String.prototype.ToInt = function () { return isNaN(parseInt(this)) ? this.toString() : parseInt(this); };
歡迎交流。