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

jQuery使用工具集

时间:2019-12-22 16:50:54      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:现在   acea   open   replace   href   简单   打开   from   compare   

//jq-util.js
$.extend({ Util:{
/* 浏览器 */ browser:{ IE: !!document.all, IE6: !!document.all && !window.XMLHttpRequest, IE7: !!document.all && /msie 7.0/gi.test(window.navigator.appVersion), IE8: !!document.all && /msie 8.0/gi.test(window.navigator.appVersion), Firefox: /firefox/gi.test(window.navigator.userAgent), Opera: /opera/gi.test(window.navigator.userAgent), Chrome: /Chrom/gi.test(window.navigator.userAgent) }, /*去除字符串首尾空格的方法*/ trim:function(str){ return str.trim ? str.trim():str.replace(/^\s+|\s+$/g,""); }, /*获取地址栏参数 * key:要查询的字段,缺省返回地址栏所有数据 * */ getQueryString: function (key) { var search=window.location.search; if(search.length<1){ return false; } if(key && search.indexOf(key)<0){ return false; } search=search.substring(1); search=decodeURI(search); var searchArr=search.split("&"); var searchJSON={}; for(var i=0;i<searchArr.length;i++){ var item=searchArr[i].split("="); searchJSON[item[0]]=item[1]; } if(key){ return searchJSON[key]; }else { return searchJSON; } }, /*获取随机数*/ getRandom:function (min,max) { return Math.floor(Math.random() * (max-min))+min+1; }, /*字符串截取*/ substring:function (str,length) { if(str.length>length){ return str.substring(0,length)+"..."; }else { return str; } }, /* 操作cookie*/ cookie: { /* 设置 */ set:function (key,val,len,unit) { if(!key || typeof val==‘undefined‘){ return false; } var cookieVal=val; if(typeof cookieVal==‘object‘){ var valArr=[]; $.each(cookieVal,function (val_k,val_v) { valArr.push(val_k+"="+val_v); }); cookieVal=valArr.join("&"); } var len=len || 1; var unit=unit || "d"; var units={ "d":len*24*60*60*1000, "h":len*60*60*1000, "m":len*60*1000, "s":len*1000 }; var dt = new Date(); dt.setTime(dt.getTime() + (units[unit])); var expires = ";expires=" + dt.toGMTString(); var path=‘;path=/‘, domain=‘‘, secure=‘‘; document.cookie=[key, ‘=‘, cookieVal, expires, path, domain, secure].join(‘‘); }, /* 获取 * key:cookie的名称,必传参数 * name:cookie中的指定值,缺省默认返回cookie下所有值 * */ get:function (key,name) { var cookieStr=document.cookie; var start=cookieStr.indexOf(key+"="); if(!key || start<0){ return false; } cookieStr=cookieStr.substring(start); var end=cookieStr.indexOf(";"); if(end>=0){ cookieStr=cookieStr.substring(0,end); } cookieStr=cookieStr.substring(key.length+1); cookieStr=decodeURIComponent(cookieStr); var keyArr=cookieStr.split("&"); if(keyArr.length<2){ return keyArr[0]; } var keyJSON={}; for(var i=0;i<keyArr.length;i++){ var item=keyArr[i].split("="); keyJSON[item[0]]=item[1]; } if(!name){ return keyJSON; }else { if(keyJSON.hasOwnProperty(name)){ return keyJSON[name]; }else { return false; } } }, /* 删除 */ del:function (key) { this.set(key,"",-365); } }, /* * window对象 */ win: { /*窗口跳转地址*/ href: function (url, time) { var time = time || 0; setTimeout(function () { window.location.href = url; }, time); }, /*打开新窗口*/ open: function (url, time) { var time = time || 0; setTimeout(function () { window.open(url); }, time); }, /*回退历史记录*/ back: function () { window.history.back(); }, /*刷新当前页面*/ read: function (time) { var time = time || 0; setTimeout(function () { window.location.reload(); }, time); } }, /** * 校验 * @param {Object} key * @param {Object} val */ verify:function (key,val) { var regs={ /* 邮箱 */ "email":/^[0-9a-zA-Z_]+@[0-9a-zA-Z_]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$/, /* 手机 */ "mobile":/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/, /* 超链接 */ "url":/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i, /* 身份证 */ "idCard":/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/, /* 邮政编码 */ "postal":/^[1-9]\d{5}(?!\d)$/, /* YY-MM-dd 格式日期 */ "date":/^[1-2][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9]$/, /* QQ */ "qq":/^[1-9][0-9]{4,9}$/, /* 全部为数字 */ "numAll":/^\d+$/, /* 适合的帐号 英文/数字 */ "befitName":/^[a-z0-9A-Z]+$/i, /* 适合的密码 英文/数字/下划线 */ "befitPwd":/^[0-9a-zA-Z_]+$/, /* 是否包含中文 */ "chinese":/[\u4e00-\u9fa5]/, /* IP地址有效性 */ ‘ip‘:/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ }; return regs[key].test(val); }, /** * 不为空 * @param {Object} val */ isNotEmpty: function(val){ return !this.isEmpty(val); }, /** * 是否为空 * @param {Object} val */ isEmpty: function(val){ if ((val==null || typeof(val)=="undefined")|| (typeof(val)=="string"&&val==""&&val!="undefined")){ return true; }else{ return false; } }, /** * 去除元素内所有内容 strIds:"#id1,#id2,#id3" * @param {Object} strIds */ emptyHtml: function(strIds){ try{ var ids = strIds.trim(",").split(","); $(ids).each(function(){ var obj = $(this.toString()); if(obj.length>0){ $(obj).each(function(){ $(this).html(""); }); }else{ obj.html(""); } }); }catch(ex){ throw new Error("js方法:【emptyHtml(strIds)】,error!"); } }, /** * 去除元素的值 strIds:"#id1,#id2,#id3" * @param {Object} strIds */ emptyValue: function(strIds){ try{ var ids = strIds.trim(",").split(","); $(ids).each(function(){ var obj = $(this.toString()); if(obj.length>0){ $(obj).each(function(){ $(this).val(""); }); }else{ obj.val(""); } }); }catch(ex){ throw new Error("js方法:【emptyValue(strIds)】,error!"); } }, /** * 去除Textarea内所有内容 strIds:"#id1,#id2,#id3" * @param {Object} strIds */ emptyTextarea: function(strIds){ try{ var ids = strIds.trim(",").split(","); $(ids).each(function(){ var obj = $(this.toString()); if(obj.length>0){ $(obj).each(function(){ $(this).empty(); $(this).val(""); }); }else{ obj.empty(); obj.val(""); } }); }catch(ex){ throw new Error("js方法:【emptyTextarea(strIds)】,error!"); } }, /** * 18位身份证简单校验 * @param {Object} idCard */ isSimpleIdCard18: function(idCard) { return /^(?:1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5])\d{4}(?:1[89]|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}(?:\d|[xX])$/.test(idCard); }, /** * 15位身份证简单校验 * @param {Object} idCard */ isSimpleIdCard15: function(idCard) { return /^(?:1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5])\d{4}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}$/.test(idCard); }, /** * 18位身份证校验码校验 * @param {Object} idCard */ checkIdCard18Code: function(idCard) { var multiplier = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; var idDatas = idCard.split(""); var len = 17; var sum = 0; for(var i = 0; i < len; i++) { sum += idDatas[i] * multiplier[i]; } var remainder = sum % 11; var checkCodeArr = [‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘]; var checkCode = checkCodeArr[remainder]; return checkCode === idCard[17]; }, /** * 18位身份证严格校验 * @param {Object} idCard */ isIdCard18: function(idCard) { //先校验格式 if(this.isSimpleIdCard18(idCard)) { //校验日期时间是否合法 var dateStr = idCard.substr(6, 8); var dateStrNew = dateStr.replace(/(\d{4})(\d{2})(\d{2})/, "$1/$2/$3"); var dateObj = new Date(dateStrNew); var month = dateObj.getMonth() + 1; if(parseInt(dateStr.substr(4, 2)) === month) { return this.checkIdCard18Code(idCard); } } return false; }, /** * 获取最大值 * @param {Object} arr */ getArrayMaxValue: function(arr) { return Math.max.apply(Math, arr); }, /** * 获取最小值 * @param {Object} arr */ getArrayMinValue: function(arr) { return Math.min.apply(Math, arr); }, /** * 判断某个值是否在数组 * @param {Object} arr * @param {Object} ele */ inArray: function(arr, ele) { var len = arr.length; for(var i = 0; i < len; i++) { if(ele === arr[i]) { return true; } } return false; }, /** * 删除数组元素 * @param {Object} arr * @param {Object} val */ removeArrayValue: function (arr, val) { for(var i = 0; i < arr.length; i++) { if(arr[i] == val) { arr.splice(i, 1); break; } } }, /** * obj转为url参数 * @param {Object} baseUrl * @param {Object} obj */ objToUrl: function(baseUrl, obj) { var parameters = ""; var url = ""; for(var key in obj) { parameters += key + "=" + obj[key] + "&"; } parameters = parameters.replace(/&$/, ""); if(/\?$/.test(baseUrl)) { url = baseUrl + parameters; } else { url = baseUrl.replace(/\/?$/, ‘?‘) + parameters; } return url; }, /** * url参数转obj,若一个字段有多个值的话,返回数组 * @param {Object} url */ parseQueryString: function(url) { var obj = {}; if(url) { url = url.replace(/#[^#]*$/, ""); var index = url.indexOf("?"); if(index != -1) { var queryStr = url.substr(index + 1); var marchResult = null; var regex = /(\w+)(=([^&#]+)?)?/g; while((marchResult = regex.exec(queryStr)) != null) { if(marchResult[1] in obj) { var values = obj[marchResult[1]]; if(values instanceof Array) { values.push(marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null); obj[marchResult[1]] = values; } else { var arr = []; arr.push(values); arr.push(marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null); obj[marchResult[1]] = arr; } } else { obj[marchResult[1]] = marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null; } } } } return obj; }, /** * 获取当前时间 */ getCurrentTime: function() { var today = new Date(); var year = today.getFullYear(); var month = today.getMonth() + 1; var day = today.getDate(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); var timeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; return timeString; }, /* * 比较时间大小 * time1>time2 return 1 * time1<time2 return -1 * time1==time2 return 0 */ compareTime: function(time1, time2) { var d1 = time1; var d2 = time2; if((typeof d1) === "string") { d1 = new Date(Date.parse(d1.replace(/-/g, "/"))); } if((typeof d2) === "string") { d2 = new Date(Date.parse(d2.replace(/-/g, "/"))); } var t1 = d1.getTime(); var t2 = d2.getTime(); if(t1 === t2) { return 0; } else if(t1 > t2) { return 1; } return -1; }, /** * 是否闰年 * @param {Object} year */ isLeapYear: function(year) { return((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); }, /* * 距离现在几天的日期:负数表示今天之前的日期,0表示今天,整数表示未来的日期 * 如-1表示昨天的日期,0表示今天,2表示后天 */ fromToday: function(days) { var today = new Date(); today.setDate(today.getDate() + days); var date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate(); return date; }, /** * 日期时间格式化 * @param {Object} dateTime 需要格式化的日期时间 * @param {String} pattern 格式化的模式,如yyyy-MM-dd hh(HH):mm:ss.S a k K E D F w W z Z */ formt: function(dateTime, pattern) { var date = new Date(dateTime); if(this.isEmpty(pattern)) { return date.toLocaleString(); } return pattern.replace(/([a-z])\1*/ig, function(matchStr, group1) { var replacement = ""; switch(group1) { case ‘y‘: // replacement = date.getFullYear(); break; case ‘M‘: //月份 var month = date.getMonth() + 1; replacement = (month < 10 && matchStr.length >= 2) ? "0" + month : month; break; case ‘d‘: //月份的天数 var days = date.getDate(); replacement = (days < 10 && matchStr.length >= 2) ? "0" + days : days; break; case ‘k‘: //一天中的小时数(1-24) var hours24 = date.getHours(); replacement = hours24; break; case ‘H‘: //24小时制,一天中的小时数(0-23) var hours24 = date.getHours(); replacement = (hours24 < 10 && matchStr.length >= 2) ? "0" + hours24 : hours24; break; case ‘m‘: //小时中的分钟数 var minutes = date.getMinutes(); replacement = (minutes < 10 && matchStr.length >= 2) ? "0" + minutes : minutes; break; case ‘s‘: // var seconds = date.getSeconds(); replacement = (seconds < 10 && matchStr.length >= 2) ? "0" + seconds : seconds; break; case ‘S‘: //毫秒 var milliSeconds = date.getMilliseconds(); replacement = milliSeconds; break; case ‘w‘://一年中的第几个星期 var days = this.dayOfTheYear(date); replacement = Math.ceil(days / 7); break; case ‘W‘: //一月中的第几星期(会根据实际情况来算) var days = date.getDate(); replacement = Math.ceil(days / 7); break; case ‘a‘: //上下午标识 var hours24 = date.getHours(); replacement = hours24 < 12 ? "\u4e0a\u5348" : "\u4e0b\u5348"; break; case ‘h‘: //12小时制 ,am/pm 中的小时数(1-12) var hours12 = date.getHours() % 12 || 12; //0转为12 replacement = (hours12 < 10 && matchStr.length >= 2) ? "0" + hours12 : hours12; break; case ‘K‘: //和h类型 var hours12 = date.getHours() % 12; replacement = hours12; break; default: break; } return replacement; }); }, /** * 计算一个日期是当年的第几天 * @param {Object} date */ dayOfTheYear: function(date) { var obj = new Date(date); var year = obj.getFullYear(); var month = obj.getMonth(); //从0开始 var days = obj.getDate(); var daysArr = [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; for(var i = 0; i < month; i++) { days += daysArr[i]; } return days; }, /** * 获得时区名和值 * @param {Object} dateObj */ getZoneNameValue: function(dateObj) { var date = new Date(dateObj); date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); var arr = date.toString().match(/([A-Z]+)([-+]\d+:?\d+)/); var obj = { ‘name‘: arr[1], ‘value‘: arr[2] }; return obj; }, /** * trim去掉字符串两边的指定字符,默去空格 * @param {Object} str * @param {Object} tag */ strToTrim:function(str, tag){ if (!tag) { tag = ‘\\s‘; }else { if (tag == ‘\\‘) { tag = ‘\\\\‘; } else if (tag == ‘,‘ || tag == ‘|‘ || tag == ‘;‘) { tag = ‘\\‘ + tag; }else { tag = ‘\\s‘; } } eval(‘var reg=/(^‘ + tag + ‘+)|(‘ + tag + ‘+$)/g;‘); return this.replace(reg, ‘‘); }, /** * 将一个字符串用给定的字符变成数组 * @param {Object} str * @param {Object} tag */ strToArray:function(str, tag){ if (str.indexOf(tag) != -1) { return str.split(tag); }else { if (str != ‘‘) { return [str.toString()]; }else { return []; } } }, /** * 只留下数字(0123456789) * @param {Object} str */ strToNumber:function(str){ return str.replace(/\D/g, ""); }, /** * 字符串截取后面加入... */ interceptString: function(str, len) { if(str.length > len) { return str.substring(0, len) + "..."; } else { return str; } }, /** * 保留中文 * @param {Object} str */ strToCN:function(str){ var regEx = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g; return str.replace(regEx, ‘‘); }, /** * 转成int * @param {Object} str */ strToInt:function(str){ var temp = str.replace(/\D/g, ""); return isNaN(parseInt(temp)) ? str.toString() : parseInt(temp); }, /** * 是否是以XX开头 * @param {Object} str * @param {Object} tag */ strStartsWith:function(str, tag){ return str.substring(0, tag.length) == tag; }, /** * 是否是以XX结尾 * @param {Object} str * @param {Object} tag */ strEndWith: function(str, tag){ return str.substring(str.length - tag.length) == tag; }, /** * 将str字符串的s1字符替换为s2字符 * @param {Object} str * @param {Object} s1 * @param {Object} s2 */ strReplaceAll:function(str, s1, s2){ return str.replace(new RegExp(s1,"gm"),s2); }, /** * 进入全屏模式, 判断各种浏览器,找到正确的方法 * @param {Object} element */ launchFullScreen: function (element) { if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } return true; }, /** * 退出全屏模式 */ exitFullScreen: function () { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } return false; } } }); jQuery.HashMap = function(param){ //定义长度 var length = 0; //创建一个对象 var obj = new Object(); /** * 判断Map是否为空 */ this.isEmpty = function() { return length == 0; }; /** * 判断对象中是否包含给定Key */ this.containsKey = function(key) { return(key in obj); }; /** * 判断对象中是否包含给定的Value */ this.containsValue = function(value) { for(var key in obj) { if(obj[key] == value) { return true; } } return false; }; /** *向map中添加数据 */ this.put = function(key, value) { if(!this.containsKey(key)) { length++; } obj[key] = value; }; /** * 根据给定的Key获得Value */ this.get = function(key) { return this.containsKey(key) ? obj[key] : null; }; /** * 根据给定的Key删除一个值 */ this.remove = function(key) { if(this.containsKey(key) && (delete obj[key])) { length--; } }; /** * 获得Map中的所有Value */ this.values = function() { var _values = new Array(); for(var key in obj) { _values.push(obj[key]); } return _values; }; /** * 获得Map中的所有Key */ this.keySet = function() { var _keys = new Array(); for(var key in obj) { _keys.push(key); } return _keys; }; /** * 获得Map的长度 */ this.size = function() { return length; }; /** * 清空Map */ this.clear = function() { length = 0; obj = new Object(); }; /** * 将HashMap转换为string的数据 */ this.toString = function(){ $.Util.sear }; /** * 将HashMap转换为JSON格式的数据 */ _map.toJson = function(){ return this[0]; }; }

 

jQuery使用工具集

标签:现在   acea   open   replace   href   简单   打开   from   compare   

原文地址:https://www.cnblogs.com/myitnews/p/12079973.html

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