分享一个常用的javascript静态类
废话不多说,直接奉上代码,知道干啥用的小伙伴直接带走吧。
util=function(){
return{
$:function(id){
returndocument.getElementById(id);
},
trim:function(str){
returnstr.replace(/(^\s+)|(\s+$)/g,"");
},
len:function(str){
returnstr.replace(/[^\x00-\xff]/g,'**').length;
},
format:function(str){
vararg=arguments;
returnstr.replace(/\{(\d+)\}/g,function(m,i){
returnarg[parseInt(i)+1];
});
},
each:function(object,callback,args){
varname,i=0,length=object.length;
if(args){
if(length===undefined){
for(nameinobject)
if(callback.apply(object[name],args)===false)
break;
}else
for(;i<length;)
if(callback.apply(object[i++],args)===false)
break;
}else{
if(length===undefined){
for(nameinobject)
if(callback.call(object[name],name,object[name])===false)
break;
}else
for(varvalue=object[0];
i<length&&callback.call(value,i,value)!==false;value=object[++i]){}
}
},
setCookie:function(name,value,hours,path,domain){
varstr=newString();
varnextTime=newDate();
nextTime.setHours(nextTime.getHours()+hours);
str=name+"="+escape(value);
if(hours)
str+=";expires="+nextTime.toGMTString();
if(path)
str+=";path="+path;
if(domain)
str+=";domain="+domain;
document.cookie=str;
},
getCookie:function(name){
varrs=newRegExp("(^|)"+name+"=([^;]*)(;|$)","gi").exec(document.cookie),tmp;
if(tmp=rs)
returnunescape(tmp[2]);
returnnull;
},
delCookie:function(name){
document.cookie=name+"=-1"+";expires=Fri,31Dec199923:59:59GMT;";
},
/**
*urlString
*parmsString
*methodStringdefaultvalue"get"
*asyBooleandefalutvaluetrue
*successFunction(http_request.responseText)
**/
ajax:function(config){
varurl=config.url,
parms=(config.parms?config.parms:"")+"&t="+newDate().getTime(),
method=config.method||"get",
asy=true;
varhttp_request=null;
if(method.toLowerCase()=="get"){
url=url+"?"+parms;
parms=null;
}
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest){//Mozilla浏览器
http_request=newXMLHttpRequest();
if(http_request.overrideMimeType){//设置MiME类别
http_request.overrideMimeType("text/xml");
}
}elseif(window.ActiveXObject){//IE浏览器
try{
http_request=newActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request=newActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(!http_request){//异常,创建对象实例失败
thrownewError("不能创建XMLHttpRequest对象实例.");
returnnull;
}
http_request.open(method,url,asy);
http_request.onreadystatechange=function(){
if(http_request.readyState==4){
try{
if(http_request.status==200){
config.success(http_request.responseText);
}
}catch(e){
thrownewError("数据读取失败.");
}
}
};
if(method.toLowerCase()=="post"){
http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
http_request.send(parms);
}
};
}();
是不是相当不错呢,反正我是很满意。