适合自己的,才是最好用的,插件讲究的是通用性和简洁性,介绍几款收集的比较好用的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); };
欢迎交流。