28个常用JavaScript方法集锦
经常使用的JS方法,今天记下,以便以后查询
/*手机类型判断*/
varBrowserInfo={ userAgent:navigator.userAgent.toLowerCase() isAndroid:Boolean(navigator.userAgent.match(/android/ig)), isIphone:Boolean(navigator.userAgent.match(/iphone|ipod/ig)), isIpad:Boolean(navigator.userAgent.match(/ipad/ig)), isWeixin:Boolean(navigator.userAgent.match(/MicroMessenger/ig)), }
/*返回字符串长度,汉子计数为2 */
functionstrLength(str){ vara=0; for(vari=0;i<str.length;i++){ if(str.charCodeAt(i)>255) a+=2;//按照预期计数增加2 else a++; } returna; }
获取url中的参数
functionGetQueryStringRegExp(name,url){ varreg=newRegExp("(^|\\?|&)"+name+"=([^&]*)(\\s|&|$)","i"); if(reg.test(url))returndecodeURIComponent(RegExp.$2.replace(/\+/g,""));return""; }
/*js绑定事件适用于任何浏览器的元素绑定 */
functioneventBind(obj,eventType,callBack){ if(obj.addEventListener){ obj.addEventListener(eventType,callBack,false); } elseif(window.attachEvent){ obj.attachEvent('on'+eventType,callBack); } else{ obj['on'+eventType]=callBack; } }; eventBind(document,'click',bodyClick);
/*获得当前浏览器JS的版本*/
functiongetjsversion(){ varn=navigator; varu=n.userAgent; varapn=n.appName; varv=n.appVersion; varie=v.indexOf('MSIE'); if(ie>0){ apv=parseInt(i=v.substring(ie+5)); if(apv>3){ apv=parseFloat(i); } }else{ apv=parseFloat(v); } varisie=(apn=='MicrosoftInternetExplorer'); varismac=(u.indexOf('Mac')>=0); varjavascriptVersion="1.0"; if(String&&String.prototype){ javascriptVersion='1.1'; if(javascriptVersion.match){ javascriptVersion='1.2'; vartm=newDate; if(tm.setUTCDate){ javascriptVersion='1.3'; if(isie&&ismac&&apv>=5)javascriptVersion='1.4'; varpn=0; if(pn.toPrecision){ javascriptVersion='1.5'; a=newArray; if(a.forEach){ javascriptVersion='1.6'; i=0; o=newObject; tcf=newFunction('o','vare,i=0;try{i=newIterator(o)}catch(e){}returni'); i=tcf(o); if(i&&i.next){ javascriptVersion='1.7'; } } } } } } returnjavascriptVersion; }
/*获取当前点击事件的Object对象*/
functiongetEvent(){ if(document.all){ returnwindow.event;//如果是ie } func=getEvent.caller; while(func!=null){ vararg0=func.arguments[0]; if(arg0){ if((arg0.constructor==Event||arg0.constructor==MouseEvent) ||(typeof(arg0)=="object"&&arg0.preventDefault&&arg0.stopPropagation)){ returnarg0; } } func=func.caller; } returnnull; };
/*字符串截取方法 */
getCharactersLen:function(charStr,cutCount){ if(charStr==null||charStr=='')return''; vartotalCount=0; varnewStr=''; for(vari=0;i<charStr.length;i++){ varc=charStr.charCodeAt(i); if(c<255&&c>0){ totalCount++; }else{ totalCount+=2; } if(totalCount>=cutCount){ newStr+=charStr.charAt(i); break; } else{ newStr+=charStr.charAt(i); } } returnnewStr; }
/* JS弹出新窗口全屏 */
vartmp=window.open("about:blank","","fullscreen=1") tmp.moveTo(0,0); tmp.resizeTo(screen.width+20,screen.height); tmp.focus(); tmp.location.href='http://www.che168.com/pinggu/eva_'+msgResult.message[0]+'.html'; varconfig_="left=0,top=0,width="+(window.screen.Width)+",height="+(window.screen.Height); window.open('http://www.che168.com/pinggu/eva_'+msgResult.message[0]+'.html',"winHanle",config_); //模拟form提交打开新页面 varf=document.createElement("form"); f.setAttribute('action','http://www.che168.com/pinggu/eva_'+msgResult.message[0]+'.html'); f.target='_blank'; document.body.appendChild(f); f.submit();
/* 全选/全不选 */
functionselectAll(objSelect){ if(objSelect.checked==true){ $("input[name='chkId']").attr("checked",true); $("input[name='chkAll']").attr("checked",true); } elseif(objSelect.checked==false){ $("input[name='chkId']").attr("checked",false); $("input[name='chkAll']").attr("checked",false); } }
/*js判断浏览器 */
判断是否是IE浏览器 if(document.all){ alert(”IE浏览器”); }else{ alert(”非IE浏览器”); } if(!!window.ActiveXObject){ alert(”IE浏览器”); }else{ alert(”非IE浏览器”); } 判断是IE几 varisIE=!!window.ActiveXObject; varisIE6=isIE&&!window.XMLHttpRequest; varisIE8=isIE&&!!document.documentMode; varisIE7=isIE&&!isIE6&&!isIE8; if(isIE){ if(isIE6){ alert(”ie6″); }elseif(isIE8){ alert(”ie8″); }elseif(isIE7){ alert(”ie7″); } }
/*判断浏览器*/
functiongetOs(){ if(navigator.userAgent.indexOf("MSIE8.0")>0){ return"MSIE8"; } elseif(navigator.userAgent.indexOf("MSIE6.0")>0){ return"MSIE6"; } elseif(navigator.userAgent.indexOf("MSIE7.0")>0){ return"MSIE7"; } elseif(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ return"Firefox"; } if(navigator.userAgent.indexOf("Chrome")>0){ return"Chrome"; } else{ return"Other"; } }
/* JS判断两个日期大小适合2012-09-09与2012-9-9两种格式的对比 */
//得到日期值并转化成日期格式,replace(/\-/g,"\/")是根据验证表达式把日期转化成长日期格式,这样再进行判断就好判断了 functionValidateDate(){ varbeginDate=$("#t_datestart").val(); varendDate=$("#t_dateend").val(); if(beginDate.length>0&&endDate.length>0){ varsDate=newDate(beginDate.replace(/\-/g,"\/")); vareDate=newDate(endDate.replace(/\-/g,"\/")); if(sDate>eDate){ alert('开始日期要小于结束日期'); returnfalse; } } }
/*移除事件*/
this.moveBind=function(objId,eventType,callBack){ varobj=document.getElementById(objId); if(obj.removeEventListener){ obj.removeEventListener(eventType,callBack,false); } elseif(window.detachEvent){ obj.detachEvent('on'+eventType,callBack); } else{ obj['on'+eventType]=null; } }
/*回车提交*/
$("id").onkeypress=function(event){ event=(event)?event:((window.event)?window.event:"") keyCode=event.keyCode?event.keyCode:(event.which?event.which:event.charCode); if(keyCode==13){ $("SubmitLogin").onclick(); } }
/*JS执行计时器*/
timeStart=newDate().getTime(); timesEnd=newDate().getTime(); document.getElementById("time").innerHTML=timesEnd-timeStart;
/*JS写Cookie*/
functionsetCookie(name,value,expires,path,domain){ if(!expires)expires=-1; if(!path)path="/"; vard=""+name+"="+value; vare; if(expires<0){ e=""; } elseif(expires==0){ varf=newDate(1970,1,1); e=";expires="+f.toUTCString(); } else{ varnow=newDate(); varf=newDate(now.getTime()+expires*1000); e=";expires="+f.toUTCString(); } vardm; if(!domain){ dm=""; } else{ dm=";domain="+domain; } document.cookie=name+"="+value+";path="+path+e+dm; };
/*JS读Cookie */
functionreadCookie(name){ varnameEQ=name+"="; varca=document.cookie.split(';'); for(vari=0;i<ca.length;i++){ varc=ca[i]; while(c.charAt(0)=='')c=c.substring(1,c.length); if(c.indexOf(nameEQ)==0){ returndecodeURIComponent(c.substring(nameEQ.length,c.length)) } }returnnull }
/* Ajax请求 */
C.ajax=function(args){ varself=this; this.options={ type:'GET', async:true, contentType:'application/x-www-form-urlencoded', url:'about:blank', data:null, success:{}, error:{} }; this.getXmlHttp=function(){ varxmlHttp; try{ xmlhttp=newXMLHttpRequest(); } catch(e){ try{ xmlhttp=newActiveXObject("Msxml2.XMLHTTP"); } catch(e){ xmlHttp=newActiveXObject("Microsoft.XMLHTTP"); } } if(!xmlhttp){ alert('您的浏览器不支持AJAX'); returnfalse; } returnxmlhttp; }; this.send=function(){ C.each(self.options,function(key,val){ self.options[key]=(args[key]==null)?val:args[key]; }); varxmlHttp=newself.getXmlHttp(); if(self.options.type.toUpperCase()=='GET'){ xmlHttp.open(self.options.type,self.options.url+(self.options.data==null?"":((/[?]$/.test(self.options.url)?'&':'?')+self.options.data)),self.options.async); } else{ xmlHttp.open(self.options.type,self.options.url,self.options.async); xmlHttp.setRequestHeader('Content-Length',self.options.data.length); } xmlHttp.setRequestHeader('Content-Type',self.options.contentType); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4){ if(xmlHttp.status==200||xmlHttp.status==0){ if(typeofself.options.success=='function')self.options.success(xmlHttp.responseText); xmlHttp=null; } else{ if(typeofself.options.error=='function')self.options.error('ServerStatus:'+xmlHttp.status); } } }; xmlHttp.send(self.options.type.toUpperCase()=='POST'?self.options.data.toString():null); }; this.send(); };
/* JSStringBuilder用法 */
functionStringBuilder(){ this.strings=newArray; }; StringBuilder.prototype.append=function(str){ this.strings.push(str); }; StringBuilder.prototype.toString=function(){ returnthis.strings.join(''); };
/*JS加载到顶部LoadJS */
functionloadJS(url,fn){ varss=document.getElementsByName('script'), loaded=false; for(vari=0,len=ss.length;i<len;i++){ if(ss[i].src&&ss[i].getAttribute('src')==url){ loaded=true; break; } } if(loaded){ if(fn&&typeoffn!='undefined'&&fninstanceofFunction)fn(); returnfalse; } vars=document.createElement('script'), b=false; s.setAttribute('type','text/javascript'); s.setAttribute('src',url); s.onload=s.onreadystatechange=function(){ if(!b&&(!this.readyState||this.readyState=='loaded'||this.readyState=='complete')){ b=true; if(fn&&typeoffn!='undefined'&&fninstanceofFunction)fn(); } }; document.getElementsByTagName('head')[0].appendChild(s); }, bind:function(objId,eventType,callBack){ //适用于任何浏览器的绑定 varobj=document.getElementById(objId); if(obj.addEventListener){ obj.addEventListener(eventType,callBack,false); } elseif(window.attachEvent){ obj.attachEvent('on'+eventType,callBack); } else{ obj['on'+eventType]=callBack; } } functionJSLoad(args){ s=document.createElement("script"); s.setAttribute("type","text/javascript"); s.setAttribute("src",args.url); s.onload=s.onreadystatechange=function(){ if(!s.readyState||s.readyState=="loaded"||s.readyState=="complete"){ if(typeofargs.callback=="function")args.callback(this,args); s.onload=s.onreadystatechange=null; try{ s.parentNode&&s.parentNode.removeChild(s); }catch(e){} } }; document.getElementsByTagName("head")[0].appendChild(s); }
/* 清空LoadJS加载到顶部的js引用 */
functionClearHeadJs (src){ varjs=document.getElementsByTagName('head')[0].children; varobj=null; for(vari=0;i<js.length;i++){ if(js[i].tagName.toLowerCase()=="script"&&js[i].attributes['src'].value.indexOf(src)>0){ obj=js[i]; } } document.getElementsByTagName('head')[0].removeChild(obj); };
/* JS替换非法字符主要用在密码验证上出现的特殊字符 */
functionURLencode(sStr){ returnescape(sStr).replace(/\+/g,'%2B').replace(/\"/g,'%22').replace(/\'/g,'%27').replace(/\//g,'%2F'); };
/* 按Ctrl+Entert直接提交表单 */
document.body.onkeydown=function(evt){ evt=evt?evt:(window.event?window.event:null); if(13==evt.keyCode&&evt.ctrlKey){ evt.returnValue=false; evt.cancel=true; PostData(); } };
/*获取当前时间 */
functionGetCurrentDate(){ vard=newDate(); vary=d.getYear()+1900; month=add_zero(d.getMonth()+1), days=add_zero(d.getDate()), hours=add_zero(d.getHours()); minutes=add_zero(d.getMinutes()), seconds=add_zero(d.getSeconds()); varstr=y+'-'+month+'-'+days+''+hours+':'+minutes+':'+seconds; returnstr; }; functionadd_zero(temp){ if(temp<10)return"0"+temp; elsereturntemp; }
/*Js去掉空格方法: */
String.prototype.Trim=function() {returnthis.replace(/(^\s*)|(\s*$)/g,"");} String.prototype.LTrim=function() {returnthis.replace(/(^\s*)/g,"");} String.prototype.RTrim=function() {returnthis.replace(/(\s*$)/g,"");}
/*js动态移除head里的js引用 */
this.ClearHeadJs=function(src){ varjs=document.getElementsByTagName('head')[0].children; varobj=null; for(vari=0;i<js.length;i++){ if(js[i].tagName.toLowerCase()=="script"&&js[i].attributes['src'].value.indexOf(src)>0){ obj=js[i]; } } document.getElementsByTagName('head')[0].removeChild(obj); };
/* 整个UL点击事件 加在UL里的onclick里*/
functionCreateFrom(url,params){ varf=document.createElement("form"); f.setAttribute("action",url); for(vari=0;i<params.length;i++){ varinput=document.createElement("input"); input.setAttribute("type","hidden"); input.setAttribute("name",params[i].paramName); input.setAttribute("value",params[i].paramValue); f.appendChild(input); } f.target="_blank"; document.body.appendChild(f); f.submit(); };
/*判断浏览器使用的是哪个JS版本*/
<scriptlanguage="javascript"> varjsversion=1.0; </script> <scriptlanguage="javascript1.1"> jsversion=1.1; </script> <scriptlanguage="javascript1.2"> jsversion=1.2; </script> <scriptlanguage="javascript1.3"> jsversion=1.3; </script> <scriptlanguage="javascript1.4"> jsversion=1.4; </script> <scriptlanguage="javascript1.5"> jsversion=1.5; </script> <scriptlanguage="javascript1.6"> jsversion=1.6; </script> <scriptlanguage="javascript1.7"> jsversion=1.7; </script> <scriptlanguage="javascript1.8"> jsversion=1.8; </script> <scriptlanguage="javascript1.9"> jsversion=1.9; </script> <scriptlanguage="javascript2.0"> jsversion=2.0; </script> alert(jsversion);
以上就是本文的全部内容了,希望能对大家有所帮助,也不枉整理这么久了,呵呵。