封装自己的Common.js工具库

时间:2023-12-25 17:20:43
Code/**
* Created by LT on 2013/6/16.
* Common.js
* 对原生JS对象的扩展
* Object、Array、String、Date、Ajax、Cookie
*/ ;(function(){
Object.extend =function(targetObj,fnJson){
for(var fnName in fnJson){
targetObj[fnName]=fnJson[fnName];
}
return targetObj;
}; /**
* 对Object的扩展
*/
Object.extend(Object.prototype,{
values: function() { // 一个静态方法, 传入一个对象, 返回该对象中所有属性所对应的值, 构成数组返回
var values = [];
for (var property in this) values.push(this[property]); // 将每个属性的值压入到一个数组中
return values;
},
clone: function(object) { // 一个静态方法, 传入一个对象, 克隆一个新对象并返回
return Object.extend({}, object);
},
getType:function(){
return Object.prototype.toString.call(this).match(/\[object (.*?)\]/)[1].toLowerCase();
},
toJson:function(){
return JSON.stringify(this);
},
serialize:function(){
if(JSON.parse)
return JSON.parse(this);
switch(this.constructor){
case Object:
var str = "{";
for(var o in obj){
str += '"'+o + '"'+ ":" + Serialize(obj[o]) +",";
}
if(str.substr(str.length-1) == ",")
str = str.substr(0,str.length -1);
return str + "}";
break;
case Array:
var str = "{";
if(str.substr(str.length-1) == ",") {
str = str.substr(0, str.length - 1);
}
for(var o in obj){
str += '"'+o + '"'+ ":"+Serialize(obj[o]) +",";
}
return str + "}";
break;
case Boolean:
return "\"" + obj.toString() + "\"";
break;
case Date:
return "\"" + obj.toString() + "\"";
break;
case Function:
break;
case Number:
return "\"" + obj.toString() + "\"";
break;
case String:
return "\"" + obj.toString() + "\"";
break;
}
}
}); /**
* 对Array的扩展
*/
Object.extend(Array.prototype,{
clear:function(){
this.length=0;
return this;
},
lastIndexOfArr:function(obj){
if(this.lastIndexOf(obj)){
return this.lastIndexOf(obj);
}else{
this.reverse();
return this.length-1-this.indexOfArr(obj);
}
},
contain:function(obj){
return this.indexOfArr(obj)>-1;
},
insertAt:function(index,obj){
this.splice(index,0,obj);
return this;
},
removeAt:function(index){
this.splice(index,1);
return this;
},
first:function(){
return this[0];
},
indexOfArr:function(obj){
//如果浏览器支持原生的indexOf,则调用原生的方法
if(this.indexOf){
return this.indexOf(obj);
}else{
var i=0;len=this.length;
for(i;i<len;i++){
if(this[i]==obj)
return i;
return -1;
}
}
},
last:function(){
return this[this.length-1];
},
distinct:function(){
this.sort();
var res=[this[0]];
for(var i = 1; i < this.length; i++)
{
if( this[i] !== res[res.length-1])
{
res.push(this[i]);
}
}
return res;
},
sumNum:function(){
if(this.reduce){
return this.reduce(function(partial,value){
return partial+value;
})
}else{
return eval(arr.join('+'));
}
},
sortNumAsc:function(){
this.sort(function(a,b){
return a-b;
});
return this;
},
sortNumDesc:function(){
this.sort(function(a,b){
return b-a;
});
return this;
},
maxNum:function(){
return this.sortNumAsc()[this.length-1];
},
minNum:function(){
return this.sortNumAsc()[0];
},
toUpperCase:function(){
if(this.map){
return this.map.call(this,function(elem){
return elem.toUpperCase();
})
}else{
return this.toLocaleString().toUpperCase().split(',');
}
},
toLowerCase:function(){
if(this.map){
return this.map.call(this,function(elem){
return elem.toLowerCase();
})
}else{
return this.toLocaleString().toLowerCase().split(',');
} }
}) /**
* 对String的扩展
*/
Object.extend(String.prototype,{
/*
*使用示例如下
*var s = String.format("S{0}T{1}","n","e");//结果:SnTe
*/
format:function(){
var res = arguments[0];
for(var i= 0,len=arguments.length-1; i<len; i++){
var b=new Regexp("\\{"+i+"\\","gm");
res= res.replace(b,arguments[i+1]);
}
return res;
},
append:function(str){
return this.concat(str);
},
leftpad:function(len,str){
if(arguments.length===1) str='0';
var res = new StringBuilder();
for (var i= 0,c=len-this.length; i<c; i++){
res.append(str);
}
res.append(this);
return res.toString();
},
rightpad:function(len, str){
if(arguments.length===1) str='0';
var res = new StringBuilder();
res.append(this);
for (var i= 0,c=len-this.length; i<c; i++){
res.append(str);
}
return res.toString();
},
trim:function(){
return this.replace(/(^\s+)|(\s+$)/g,'');
},
ltrim:function(){
return this.replace(/^\s+/g,'');
},
rtrim:function(){
return this.replace(/\s+$/g,'');
},
startWith:function(str,ignorCase){
if(str.length>this.length)return false;
if(ignorCase){
return this.toLowerCase().indexOf(str.toLowerCase())===0;
}else{
return this.indexOf(str)===0;
}
},
endWith:function(str,ignorCase){
if(str.length>this.length)return false;
if(ignorCase){
return this.toLowerCase().lastIndexOf(str.toLowerCase())===this.length-str.length;
}else{
return this.lastIndexOf(str)===this.length-str.length;
}
},
removeCharAt:function(index){
if (index < 0 || index >= this.length) {
return this.valueOf();
}
else if (index == 0) {
return this.substring(1, this.length);
}
else if (index == this.length - 1) {
return this.substring(0, this.length - 1);
}
else {
return this.substring(0, index) + this.substring(index + 1);
}
},
removeStr:function(start,end){
if (start == end) {
return this.deleteCharAt(start);
}
else {
if (start > end) {
var temp = start;
start = end;
end = temp;
}
if (start < 0) {
start = 0;
}
if (end > this.length - 1) {
end = this.length - 1;
}
return this.substring(0, start) + this.substring(end +1 , this.length);
} },
equalIgnoreCase:function(str){
return this.toLowerCase()===str.toLowerCase();
},
insertAfter:function(index,str){
return this.slice(0,index+1)+str+this.slice(index+1);
},
insertBefore:function(index,str){
return this.slice(0,index)+str+this.slice(index);
},
isAllNumber:function(){
for (var i = 0; i < this.length; i++) {
if (this.charAt(i) < '0' || this.charAt(i) > '9') {
return false;
}
}
return true;
},
isInt:function(){
return /^[1-9]\d$/.test(this);
},
isNullOrEmpty:function(){
if(this===null||this.trim()===""){
return true;
}
return false;
},
isPhoneNum:function(){
var pattern = /^0{0,1}(13[0-9]|14[6|7]|15[0-3]|15[5-9]|18[0-3]|18[5-9])[0-9]{8}$/;
return pattern.test(this);
},
getCharLength:function(){
var temp = 0;
for (var i = 0; i < this.length; i++) {
if (this.charCodeAt(i) > 255) {
temp += 2;
}
else {
temp += 1;
}
}
return temp;
},
getNum:function(){
return this.replace(/[^d]/g, "");
},
getEn:function(){
return this.replace(/[^A-Za-z]/g, "");
},
getCn:function(){
return this.replace(/[^u4e00-u9fa5uf900-ufa2d]/g, "");
},
left:function(n){
return this.slice(0, n);
},
right:function(n){
return this.slice(this.length - n);
},
encodeHTML:function(){
if(this.isNullOrEmpty()) return this;
var str = this; str=str.replace(/&/g,"&amp;");
str=str.replace(/</g,"&lt;");
str=str.replace(/>/g,"&gt;");
str=str.replace(/\'/g,"&apos;");
str=str.replace(/\"/g,"&quot;");
str=str.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;");
str=str.replace(/\s+/g," ");
str=str.replace(/\s/g,"&nbsp;");
str=str.replace(/\n/g,"&BR"); return str; },
decodeHTML:function(){
if(this.isNullOrEmpty()) return this;
var str = this; str=str.replace(/&amp;/g,"&");
str=str.replace(/&lt;/g,"<");
str=str.replace(/&gt;/g,">");
str=str.replace(/&apos;/g,"\'");
str=str.replace(/&quot;/g,"\"");
str=str.replace(/&nbsp;&nbsp;&nbsp;&nbsp;/g,"\t");
str=str.replace(/&nbsp;/g," ");
str=str.replace(/&BR/g,"\r\n"); return str;
},
truncate:function(len,str){
if(this.length<=len){
return this;
}else{
return this.substring(0,len)+str;
}
},
getUrlQuery:function(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = this.substr(this.indexOf("\?") + 1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
appendUrlPram:function(name,val){
var index = this.indexOf(name + '=');
if (index > 0) {
var endPos = this.indexOf('&', index);
if (endPos > index) return this.replace('/' + this.substr(index, endPos - index) + '/', name + '=' + val);
else return this.substr(0, index) + name + '=' + val;
}
else return this.indexOf('?') > 0 ? (this + '&' + name + '=' + val) : (this + '?' + name + '=' + val);
}
}); /**
* 添加StringBuilder类,提高对字符串操作的效率
*/
function StringBuilder(str){
this._strings= new Array();
this.append(str);
}
Object.extend(StringBuilder.prototype,{
append:function(str){
this._strings.push(a);
return this;
},
toString:function(){
var a = (arguments.length==0)?"":arguments[0];
return this._strings.join(a);
}
}); /**
* 对Date的扩展方法
*/
Object.extend(Date.prototype,{
format:function(formatStr){
var o = {
'M+':this.getMonth()+1,//月
'd+':this.getDate(),//日
'h+':this.getHours(),//小时
'm+':this.getMinutes(),//分
's+':this.getSeconds(),//秒
'q+':Math.floor((this.getMonth()+3)/3),//季度
'S':this.getMilliseconds() //毫秒
}
if(/(y+)/.test(formatStr)){
formatStr = formatStr.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for(var k in o){
if (new RegExp("(" + k + ")").test(fomartStr))
formatStr = formatStr.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return formatStr;
}
},
addDays:function(num){
this.setDate(this.getDate+num);
return this;
},
addWeeks:function(num){
return this.addDays(num*7);
},
addMonths:function(num){
var d = this.getDate();
this.setMonth(this.getMonth()+num);
if(this.getDate<d){
this.setDate(0);
}
return this;
},
addYears:function(num){
var m = this.getMonth();
this.setFullYear(this.getFullYear()+num);
if(m<this.getMonth()){
this.setDate(0);
}
return this;
},
isValiDate:function(dateStr,formatStr){
if(!dateStr){
return false;
}
if(!formatStr){
formatStr = "yyyy-MM-dd";//默认格式:yyyy-MM-dd
}
if(dateStr.length!=formatStr.length){
return false;
}else{
if(formatStr=="yyyy-MM-dd"||formatStr=="YYYY-MM-DD"){
var r1=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8]))))))$/;
return r1.test(dateStr);
}else if(formatStr=="yyyy/MM/dd"||formatStr=="YYYY/MM/DD"){
var r2=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))\/((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))\/((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/(([0-1][0-9])|(2[0-8]))))))$/;
return r2.test(dateStr);
}else if(formatStr=="MM-dd-yyyy"||formatStr=="MM-DD-YYYY"){
var r3=/^((((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9])))-(((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8])))))-d{2}(([02468][1235679])|([13579][01345789])))$/;
return r3.test(dateStr);
}else if(formatStr=="MM/dd/yyyy"||formatStr=="MM/DD/YYYY"){
var r4=/^((((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/([0-2][0-9])))\/(((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))\/(([0-2][0-9])|(3[01])))|(((0[469])|(11))\/(([0-2][0-9])|(30)))|(02\/(([0-1][0-9])|(2[0-8])))))\/d{2}(([02468][1235679])|([13579][01345789])))$/;
return r4.test(dateStr);
}else{
// throw new Error('日期格式不正确');
return false;
}
}
return false;
},
isValiTime:function(timeStr, formatStr){
if(!timeStr){
return false;
}
if(!formatStr){
formatStr = "hh:mm:ss";//默认格式:hh:mm:ss
}
if(timeStr.length!=formatStr.length){
return false;
}else{
if(formatStr=="hh:mm:ss"){
var r1=/^(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])$/;
return r1.test(timeStr);
}else if(formatStr=="hh-mm-ss"){
var r2=/^(([0-1][0-9])|(2[0-3]))-([0-5][0-9])-([0-5][0-9])$/;
return r2.test(timeStr);
}else if(formatStr=="hh/mm/ss"){
var r3=/^(([0-1][0-9])|(2[0-3]))\/([0-5][0-9])\/([0-5][0-9])$/;
return r3.test(timeStr);
}else{
// throw new Error("时间格式不正确!");
return false;
}
}
return false;
},
isValiDateTime:function(dateTimeStr){
var dateTimeReg=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8]))))))(s{1}(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9]))?$/
return dateTimeReg.test(dateTimeStr);
},
isLeapYear:function(){
return (this.getYear()%4==0&&((this.getYear()!=0)||(this.getYear()%400==0)));
},
daysBetween:function(dateOne,dateTwo){
if((dateOne instanceof Date)==false||(dateTwo instanceof Date)==false){
return 0;
}else{
return Math.abs(Math.floor((dateOne.getTime()-dateTwo.getTime())/1000/60/60/24));
}
},
dateDiff:function(dtEnd, field){
var dtStart = this;
if((dtEnd instanceof Date)==false){
return 0;
}else{
if(!field){
field = "d";
}
switch(field){
case 'Y':
case 'y':return dtEnd.getFullYear() - dtStart.getFullYear();break;
case 'M':return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);break;
case 'W':
case 'w':return parseInt((dtEnd - dtStart) / (86400000 * 7));break;
case 'D':
case 'd':return parseInt((dtEnd - dtStart) / 86400000);break;
case 'H':
case 'h':return parseInt((dtEnd - dtStart) / 3600000);break;
case 'm':return parseInt((dtEnd - dtStart) / 60000);break;
case 'S':
case 's':return parseInt((dtEnd - dtStart) / 1000);break;
default: return 0;
}
return 0;
}
},
toArray:function(){
var myArray = new Array();
myArray[0] = this.getFullYear();
myArray[1] = this.getMonth();
myArray[2] = this.getDate();
myArray[3] = this.getHours();
myArray[4] = this.getMinutes();
myArray[5] = this.getSeconds();
return myArray;
},
datePart:function(field){
if(!field){
field = "d";
}
var Week = ['日','一','二','三','四','五','六'];
switch (field){
case 'Y' :
case 'y' :return this.getFullYear();break;
case 'M' :return (this.getMonth()+1);break;
case 'W' :
case 'w' :return Week[this.getDay()];break;
case 'D' :
case 'd' :return this.getDate();break;
case 'H' :
case 'h' :return this.getHours();break;
case 'm' :return this.getMinutes();break;
case 's' :return this.getSeconds();break;
default:return this.getDate();
}
return this.getDate();
}
}); /**
* 对ajax的扩展
* 调用示例:
* new HttpAjax({
type:"get",
url:"testAjax.php",
data:{"name":'Jack'},
success:function(data){
console.log(data);
},
failure:function(data){
console.log(data);
},
isAsyn:false
});
*/
HttpAjax = (function(){
function HttpAjax(options){
var settings={
type:'post', //请求类型
url:'', //请求地址
data:{"id":-1}, //json格式的参数
success:function(){},//成功的回调函数
failure:function(){},//失败的回调函数
isAsyn:true //是否为异步
};
this.options = Object.extend(settings,options); Object.extend(HttpAjax.prototype,{
_createXhr:function(){
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
else if (typeof ActiveXObject !== 'undefined') {
var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp'];
for (var i = 0, len = versions.length; i < len; i++) {
try {
var xhr = new ActiveXObject(versions[i]);
this.IsCreateOk = versions[i];
return xhr;
}
catch (e) { }
}
if (typeof this.IsCreateOk === 'undefined') {
throw new Error("您的浏览器版本过低,无法创建异步对象,请升级您的浏览器!");
}
}
},
_encodeData:function(paramters){
var data = [];
for (var name in paramters) {
//将数组中的数据以=拼接后再添加到data数组中 [name=aa,age=11]
var _regesp = /%20/g; //空格的正则表达式
var _value = paramters[name].toString(); //获取值
data.push(encodeURIComponent(name).replace(_regesp, '+') + "=" + encodeURIComponent(_value).replace(_regesp, '+'));
}
//以&将数组元素拼接后返回 如:name=aa&age=11
return data.join("&");
},
_regCallback:function(xhr){
var _this=this;
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) {
_this.options.success(_this._getResponseData(xhr), xhr.statusText);
} else {
_this.options.failure(xhr.status, xhr.statusText);
}
}
}
},
_getResponseData:function(xhr){
var responseType = xhr.getResponseHeader("Content-Type");
switch (responseType) {
case 'text/xml':
return xhr.responseXML;
case 'text/json':
case 'text/javascript':
case 'application/javascript':
case 'application/x-javascript':
return eval('(' + xhr.responseText + ')');
default:
return xhr.responseText;
};
},
_init:function(options){
this.options=options;
if(this.options.url=="") return;
this.xhr = this._createXhr();//创建异步对象
this._regCallback(this.xhr);//注册回调事件 //根据请求类型,发送异步请求
if(this.options.type.toLowerCase()=="post"){
this._post(this.xhr);
}
else{
this._get(this.xhr);
}
},
_post:function(xhr){
this.xhr=xhr;
this.data=this._encodeData(this.options.data);
this.url=this.options.url+"?d=" + parseInt(Math.random()*100+1,10);
this.asyn=!!this.options.isAsyn; xhr.open("POST", this.url, this.asyn);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(this.data);
},
_get:function(xhr){
this.xhr=xhr;
this.data=this._encodeData(this.options.data);
this.url=this.options.url+'?' + this.data + '&d=' + parseInt(Math.random()*100+1,10);
this.asyn=!!this.options.isAsyn; xhr.open('GET', this.url, this.asyn);
xhr.send(null);
}
});
this._init(this.options);
};
return HttpAjax;
})(window); /**
* 对cookie的扩展
*/
Object.extend(Document.cookie.prototype,{
setCookie:function(name,value,days){
var d = new Date();
d.setDate(d.getDate()+days);
document.cookie=name+'='+value+';expires'+d;
},
getCookie:function(name){
var arr = document.cookie.split(',');
for(var i= 0,len=arr.length; i<len; i++){
var keyV = arr[i].split('=');
if(keyV[0]==name){
return keyV[1];
}
}
return '';
},
removeCookie:function(name){
setCookie(name,'',-1);
}
}); })(window)

有百分之六十是在网络收集而来的,因为平时用的多,但是又没有时间好好总结一下,今天终于总结到一起了,部分方法没有测试,如若有误,请指正!