zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js常用函数2008-8-16整理

JS 函数 常用 整理 16 2008
2023-06-13 09:14:01 时间

//js常用函数更新2008-8-16取自网络

function$(id){
returndocument.getElementById(id);
}


/**************
函数:getElementsByClassName
使用方法:
获取document内的超链接class是“info-links”的。
getElementsByClassName(document,"a","info-links");
获取container内的div的class是col的.
getElementsByClassName(document.getElementById("container"),"div","col");
获取document内的所有class是“click-me”的。
getElementsByClassName(document,"*","click-me");
返回一个数组
**************/
functiongetElementsByClassName(oElm,strTagName,strClassName){
vararrElements=(strTagName=="*"&&oElm.all)?oElm.all:oElm.getElementsByTagName(strTagName);
vararrReturnElements=newArray();
strClassName=strClassName.replace(/-/g,"\-");
varoRegExp=newRegExp("(^|\s)"+strClassName+"(\s|$)");
varoElement;
for(vari=0;i<arrElements.length;i++){
oElement=arrElements[i];
if(oRegExp.test(oElement.className))
arrReturnElements.push(oElement);
}
return(arrReturnElements)
}





/**************
replaceAll:
替换字符串中的字符。
用法:
yourstring.replaceAll("要替换的字符","替换成什么");
例子:
"cssrain".replaceAll("s","a");
"cssrain".replaceAll("","");
**************/
String.prototype.replaceAll=function(AFindText,ARepText){
raRegExp=newRegExp(AFindText,"g");
returnthis.replace(raRegExp,ARepText);
}


/**************
*字符串前后空格处理。
*如果想替换中间的空格,请用replaceAll方法。
*用法:
*"cssrain".trim();
**************/
String.prototype.trim=function()
{
returnthis.replace(/(^\s*)|(\s*$)/g,"");//将字符串前后空格,用空字符串替代。
}


/**************
*计算字符串的真正长度
//String有个属性length,但是它不能区分英文字符,
//计算中文字符和全角字符。但是在数据存储的时候中文和全角都是用两个字节来存储的,
//所有需要额外处理一下。自己写了个函数,返回String正真的长度.
用法:
<inputtype="text"name="rain"id="rain"/>
<inputtype="button"id="test"value="test"onclick="alert(document.getElementById("rain").value.codeLength())"/>
**************/
String.prototype.codeLength=function(){
varlen=0;
if(this==null||this.length==0)
return0;
varstr=this.replace(/(^\s*)|(\s*$)/g,"");//去掉空格
for(i=0;i<str.length;i++)
if(str.charCodeAt(i)>0&&str.charCodeAt(i)<128)
len++;
else
len+=2;
returnlen;
}


//JS获取字符串的实际长度,用来代替String的length属性
String.prototype.length=function(){
returnthis.replace(/[\u4e00-\u9fa5]+/g,"**").length;
}

/**************
//过滤HTML
//在评论的时候为了防止用户提交带有恶意的脚本,可以先过滤HTML标签,过滤掉双引号,单引号,符号&,符号<,符号
用法:
<inputtype="text"name="rain"id="rain"/>
<inputtype="button"id="test"value="test"onclick="alert(document.getElementById("rain").value.filterHtml())"/>
**************/
String.prototype.filterHtml=function(){
returnthis.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,"&gt").replace(/"/g,""").replace(/"/g,""");
}


/**************
format:
格式化时间。
用法:
yourdate.format("你的日期格式");
例子:
obj0=newDate("SunMay042008").format("yyyy-MM-dd");
obj1=newDate().format("yyyy-MM-ddhh:mm:ss");
obj2=newDate().format("yyyy-MM-dd");
obj3=newDate().format("yyyy/MM/dd");
obj4=newDate().format("MM/dd/yyyy");
**************/
Date.prototype.format=function(format)
{
varo={
"M+":this.getMonth()+1,//month
"d+":this.getDate(),//day
"h+":this.getHours(),//hour
"m+":this.getMinutes(),//minute
"s+":this.getSeconds(),//second
"q+":Math.floor((this.getMonth()+3)/3),//quarter
"S":this.getMilliseconds()//millisecond
}
if(/(y+)/.test(format))format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4-RegExp.$1.length));
for(varkino)if(newRegExp("("+k+")").test(format))
format=format.replace(RegExp.$1,
RegExp.$1.length==1?o[k]:
("00"+o[k]).substr((""+o[k]).length));
returnformat;
}


/**************
format:
格式化数字.
例子:
varn=format_number(123456.45656,2);//.toFixed(2)也可以实现,不过不兼容FF.
alert(n);
**************/
functionformat_number(str,digit)
{
if(isNaN(str))
{
alert("您传入的值不是数字!");
return0;
}
elseif(Math.round(digit)!=digit)
{
alert("您输入的小数位数不是整数!");
return0;
}
else
returnMath.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit);
}

/**********表单操作*********/

/**************
*得到单选框选中的值。
*用法:
*<inputtype="radio"value="1"name="cssrain"/>
*<inputtype="radio"value="2"name="cssrain"checked/>
*<inputtype="radio"value="3"name="cssrain"/>
*<inputtype="button"onclick="alert(getRadioValue("cssrain"))"value="test"/>
**************/
functiongetRadioValue(radioName){
varobj=document.getElementsByName(radioName);
for(vari=0;i<obj.length;i++){
if(obj[i].checked){
returnobj[i].value;
}
}
}

/**************
*复选框全选/不选/反选
*用法:
<formid="form_a">
<inputtype="checkbox"value="1"name="a"/>
<inputtype="checkbox"value="2"name="a"checked/>
<inputtype="checkbox"value="3"name="a"/>
<inputtype="button"value="全选"onclick="checkAll(document.getElementById("form_a"),"all")"/>
<inputtype="button"value="不选"onclick="checkAll(document.getElementById("form_a"),"none")"/>
<inputtype="button"value="反选"onclick="checkAll(document.getElementById("form_a"),"")"/>
</form>
**************/
functioncheckAll(form,sel){
for(i=0,n=form.elements.length;i<n;i++){
if(form.elements[i].type=="checkbox"){
if(form.elements[i].checked==true){
form.elements[i].checked=(sel=="all"?true:false);
}else{
form.elements[i].checked=(sel=="none"?false:true);
}
}
}
}


/**************
*复选框检查是否选中。
*如果没一个选中,会返回false.
*用法:
<formid="form_a"name="form_a">
<inputtype="checkbox"value="1"name="a"/>
<inputtype="checkbox"value="2"name="a"checked/>
<inputtype="checkbox"value="3"name="a"/>
<inputtype="button"value="全选"onclick="alert(SCheckBox("form_a","a"))"/>
</form>
**************/
functionSCheckBox(_formName,_checkboxName){
varselflag={"checked":0,"cvalues":[]};
_scheckbox=eval("document."+_formName+"."+_checkboxName);
if(_scheckbox){
if(eval(_scheckbox.length)){
for(i=0;i<_scheckbox.length;i++){
if(_scheckbox[i].checked){
selflag.checked++;
selflag.cvalues.push(_scheckbox[i].value);
}
};
}elseif(_scheckbox.checked){
selflag.checked++;
selflag.cvalues.push(_scheckbox.value);
}
if(selflag.checked){
returnselflag;
}
}
returnfalse;
}

//如果控件值=原来值则清空
functionclearInput(input){
if(input.value==input.defaultValue){
input.value="";
}
}

/***************表单操作结束**********/


/**************/
//收藏到书签.(兼容IE和FF)。

functionaddBookmark(title,url){
if(window.sidebar){
window.sidebar.addPanel(title,url,"");
}elseif(document.all){
window.external.AddFavorite(url,title);
}elseif(window.opera&&window.print){
returntrue;
}
}

/**************
函数:文本框得到与失去焦点操作。
这个方法经常在文本框搜索的时候出现。
文本里显示“搜索”,然后当用户鼠标点击此文本,
文本框内容清空。如果用户没填写内容,那么文本的值又复原。
如果填写了,就显示用户填写的。
用法:
<inputtype=""value="关键字搜索"name="a"onfocus="clearTxt("a","关键字搜索")"onblur="fillTxt("a","关键字搜索")"/>
<inputtype="text"value="test"name="test"/>
**************/
functionclearTxt(id,txt){
if(document.getElementById(id).value==txt)
document.getElementById(id).value="";
return;
}
functionfillTxt(id,txt){
if(document.getElementById(id).value=="")
document.getElementById(id).value=txt;
return;
}


/**************
函数:用来判断鼠标按的是左键还是右键。(兼容IE和ff)
用法:
onmousedown="mouse_keycode(event)"
**************/
functionmouse_keycode(event){
varevent=event||window.event;
varnav=window.navigator.userAgent;
if(nav.indexOf("MSIE")>=1)//如果浏览器为IE.解释:因为document.all是IE的特有属性,所以通常用这个方法来判断客户端是否是IE浏览器,document.all?1:0;
{
if(event.button==1){alert("左键")}
elseif(event.button==2){alert("右键")}
}
elseif(nav.indexOf("Firefox")>=1)////如果浏览器为Firefox
{
if(event.button==0){alert("左键");}
elseif(event.button==2){alert("右键");}
}
else{//如果浏览器为其他
alert("other");
}
}


/**************
函数:触发某个对象的onclick事件。(兼容IE和FF)
用法:
<inputtype="button"value="aaa"id="a"onclick="alert("cssrain")"/>
<inputtype="button"value="触发ID为a的onclick事件"onclick="handerToClick("a")"/>
**************/
functionhanderToClick(objid){
varobj=document.getElementById(objid);
if(document.all){
obj.fireEvent("onclick");
}else{
vare=document.createEvent("MouseEvent");
e.initEvent("click",false,false);
obj.dispatchEvent(e);
}
}


/**************
实现按回车提交
**************/
functionQuickPost(evt,form){
varevt=window.event?window.event:evt;
if(evt.keyCode==13){
document.getElementById(form).submit();
}
}


/*********
验证是否是数字
**********/
functioncheckIsInteger(str)
{
//如果为空,则通过校验
if(str=="")
returntrue;
if(/^(\-?)(\d+)$/.test(str))
returntrue;
else
returnfalse;
}


/*------------------------------------------------------------
判断输入文本是否为身份证号码,如为不正确则提示
text-------输入的身份证号码
使用例子onBlur="isPid(this)"
------------------------------------------------------------*/
functionisPid(text)
{
varpid=text.value.Trim();
vartemp="0123456789";
vartemp1="0123456789xX";
if(pid!=""){
if(pid.length==15)
{
for(j=0;j<15;j++)
{
varch=pid.charAt(j);
if(temp.indexOf(ch)==-1)
{
alert("请输入正确的身份证号码!");
text.focus();
break;
}
}
}
elseif(pid.length==18)
{

for(j=0;j<pid.length-1;j++)
{
varch=pid.charAt(j);
if(temp.indexOf(ch)==-1)
{
alert("请输入正确的身份证号码!");
text.focus();
break;
}
}
varch1=pid.charAt(pid.length-1);
if(temp1.indexOf(ch1)==-1)
{
alert("请输入正确的身份证号码!");
text.focus();
}
}
else{
alert("身份证号码的应为15位或18位!");
text.focus();
}}
}

/*------------------------------------------------------------
判断两次密码输入是否一致
text-------新密码
name-------再次输入新密码
使用例子checkPassword(form1.newpass,form1.newpass1)
------------------------------------------------------------*/
functioncheckPassword(text,text1)
{
varnewpass=text.value.Trim();
varnewpass1=text1.value.Trim();
if(newpass!=newpass1){
alert("两次输入新密码不一致!");
text.focus();
returntrue;
}
}


/**//*------------------------------------------------------------
判断是否包含非法字符,如含非法字符则提示
text-------输入文本
addtemp----除英文和数字外还可包含的字符
name-------提示的名字
include----提示中不允许包含的字符
使用例子onBlur="compareTwoDate(this,"@_","邮件","%*$")"
------------------------------------------------------------*/
functionisChar(text,addtemp,name,include)
{
vartemp="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+addtemp;
for(j=0;j<text.value.length;j++)
{
varch=text.value.Trim().charAt(j);
if(temp.indexOf(ch)==-1)
{
alert(name+"中不允许包含""+include+""等字符!");
text.focus();
break;
}
}
}
/**//*------------------------------------------------------------
判断输入的是否为电子邮件,如含非法字符则提示
text-------输入的电子邮件
使用例子onBlur="isEmail(this)"
------------------------------------------------------------*/
functionisEmail(text)
{
varemail=text.value.Trim();
varm=email.indexOf("@");
varn=email.indexOf(".");
if(email!="")
{
if(m<1||m>email.length-3)
{
alert("请输入正确的电子邮件格式!");
text.focus();
returntrue;
}
elseif(n<m+2||n>email.length-2)
{
alert("请输入正确的电子邮件格式!");
text.focus();
returntrue;
}
}
}
/**//*------------------------------------------------------------
判断输入文本是否为空,如为空则提示
text-------输入文本
使用例子onBlur="isNull(this,"姓名")"
------------------------------------------------------------*/
functionisNull(text,name)
{
if(text.value.Trim()==null||text.value.Trim()=="")
{
alert(name+"不能为空!");
text.focus();
returntrue;
}
}

//允许被框架
functionenableFrame(){
if(top.location==self.location){
alert("该操作被管理员禁止");
document.execCommand("stop");
}
}

//禁止被框架
functiondisableFrame(obj){
if(top.location!=self.location){
window.open(obj);
}
}


//根据ID控制层的隐藏或者展开
functionshow_hide(obj){
if($(obj).style.display=="none"){
$(obj).style.display="";
}else{
$(obj).style.display="none";
}
}

/*****屏幕*******************/
//调用方法:
//WinPage.getPageWidth
//WinPage.getBody().width
varWinPage={
getPageWidth:function()
{
returndocument.body.scrollWidth||document.documentElement.scrollWidth||0;
},

getPageHeight:function()
{
returndocument.body.scrollHeight||document.documentElement.scrollHeight||0;
},

getBodyWidth:function()
{
returndocument.body.clientWidth||document.documentElement.clientWidth||0;
},

getBodyHeight:function()
{
returndocument.documentElement.clientHeight||document.body.clientHeight||0;
},

getBodyLeft:function()
{
returnwindow.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;
},

getBodyTop:function()
{
returnwindow.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0;
},

getBody:function()
{
return{
width:this.getBodyWidth(),
height:this.getBodyHeight(),
left:this.getBodyLeft(),
top:this.getBodyTop()
};
},

getScreenWidth:function()
{
returnwindow.screen.width;
},

getScreenHeight:function()
{
returnwindow.screen.height;
}
};

//测试浏览器类型//
varBrowser=newObject();

Browser.ua=window.navigator.userAgent.toLowerCase();
Browser.ie=/msie/.test(Browser.ua);
Browser.moz=/gecko/.test(Browser.ua);

/****************/

//------------------用于载入一个文件-------------//
varJsLoader={
load:function(sUrl,fCallback)
{
var_script=document.createElement("script");
_script.setAttribute("type","text/javascript");
_script.setAttribute("src",sUrl);
document.getElementsByTagName("head")[0].appendChild(_script);

if(Browser.ie)
{
_script.onreadystatechange=function()
{
if(this.readyState=="loaded"||this.readyState=="complete")
{
fCallback();
}
};
}
elseif(Browser.moz)
{
_script.onload=function()
{
fCallback();
};
}
else
{
fCallback();
}
}
};

//实现一个StringBuffer
//varsb=newStringBuffer();
//sb.append("<tableborder="1">");
//sb.append("<tr><td>A</td><td>B</td></tr>");
//sb.append("</table>")
//document.write(sb.toString());
functionStringBuffer(){
this._strings_=newArray;
}

StringBuffer.prototype.append=function(str){
this._strings_.push(str);
}

StringBuffer.prototype.toString=function(){
returnthis._strings_.join("");
}

StringBuffer.prototype.reset=function(){
this._strings_=newArray;
}