当前位置: 首页 > 图文教程 > 网络编程 > Javascript > js常用函数2008-8-16整理

Javascript
JS getMonth()日期函数的值域是0-11
jQuery 处理网页内容的实现代码
jQuery 树形结构的选择器
jQuery 处理表单元素的代码
JQuery 动画卷页 返回顶部 动画特效(兼容Chrome)
JavaScript 10件让人费解的事情
类似GMAIL的Ajax信息反馈显示
两个比较有用的Javascript工具函数代码
JavaScript Timer实现代码
JavaScript 学习技巧
JavaScript 题型问答有答案参考
js删除select中重复项的实现代码
javascript中的链式调用
JavaScript DOM学习第一章 W3C DOM简介
JavaScript DOM 学习第二章 编辑文本
JavaScript DOM 学习第三章 内容表格
JavaScript DOM学习第四章 getElementByTagNames
JavaScript DOM 学习第五章 表单简介
JavaScript DOM学习第六章 表单实例
JavaScript DOM 学习第七章 表单的扩展

Javascript 中的 js常用函数2008-8-16整理


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 125 ::
收藏到网摘: n/a

方便使用js的朋友,把下面的函数找到你想要的功能函数,复制部分判断输入文本是否为身份证号码,如为不正确则提示 //js常用函数 更新2008-8-16 取自网络
function $(id) {
return document.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");
返回一个数组
**************/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "\-");
var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
var oElement;
for(var i=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");
" cs sr ai n".replaceAll(" ", "");
**************/
String.prototype.replaceAll = function (AFindText,ARepText){
raRegExp = new RegExp(AFindText,"g");
return this.replace(raRegExp,ARepText);
}

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

/**************
* 计算字符串的真正长度
//String有个属性length,但是它不能区分英文字符,
//计算中文字符和全角字符。但是在数据存储的时候中文和全角都是用两个字节来存储的,
//所有需要额外处理一下。自己写了个函数,返回String正真的长度.
用法:
<input type="text" name="rain" id="rain" />
<input type="button" id="test" value="test" onclick="alert( document.getElementById('rain').value.codeLength() )"/>
**************/
String.prototype.codeLength=function(){
var len=0;
if(this==null||this.length==0)
return 0;
var str=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;
return len;
}

//JS获取字符串的实际长度,用来代替 String的length属性
String.prototype.length = function(){
return this.replace(/[\u4e00-\u9fa5]+/g,"**").length;
}
/**************
//过滤HTML
//在评论的时候为了防止用户提交带有恶意的脚本,可以先过滤HTML标签,过滤掉双引号,单引号,符号&,符号<,符号
用法:
<input type="text" name="rain" id="rain" />
<input type="button" id="test" value="test" onclick="alert( document.getElementById('rain').value.filterHtml() )"/>
**************/
String.prototype.filterHtml=function(){
return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");
}

/**************
format:
格式化时间。
用法:
yourdate.format("你的日期格式");
例子:
obj0 = new Date("Sun May 04 2008").format("yyyy-MM-dd");
obj1 = new Date().format("yyyy-MM-dd hh:mm:ss");
obj2 = new Date().format("yyyy-MM-dd");
obj3 = new Date().format("yyyy/MM/dd");
obj4 = new Date().format("MM/dd/yyyy");
**************/
Date.prototype.format = function(format)
{
var o = {
"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(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}

/**************
format:
格式化数字.
例子:
var n = format_number( 123456.45656 , 2 ); // .toFixed(2)也可以实现,不过不兼容FF.
alert(n);
**************/
function format_number(str,digit)
{
if(isNaN(str))
{
alert("您传入的值不是数字!");
return 0;
}
else if(Math.round(digit)!=digit)
{
alert("您输入的小数位数不是整数!");
return 0;
}
else
return Math.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit);
}
/**********表单操作*********/
/**************
* 得到单选框选中的值。
* 用法:
*<input type="radio" value="1" name="cssrain"/>
*<input type="radio" value="2" name="cssrain" checked/>
*<input type="radio" value="3" name="cssrain"/>
*<input type="button" onclick="alert(getRadioValue('cssrain'))" value="test"/>
**************/
function getRadioValue(radioName){
var obj=document.getElementsByName(radioName);
for(var i=0;i<obj.length;i++){
if(obj[i].checked){
return obj[i].value;
}
}
}
/**************
* 复选框全选/不选/反选
* 用法:
<form id="form_a">
<input type="checkbox" value="1" name="a"/>
<input type="checkbox" value="2" name="a" checked/>
<input type="checkbox" value="3" name="a"/>
<input type="button" value="全选" onclick="checkAll(document.getElementById('form_a'),'all')"/>
<input type="button" value="不选" onclick="checkAll(document.getElementById('form_a'),'none')"/>
<input type="button" value="反选" onclick="checkAll(document.getElementById('form_a'),'')"/>
</form>
**************/
function checkAll(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.
* 用法:
<form id="form_a" name="form_a">
<input type="checkbox" value="1" name="a"/>
<input type="checkbox" value="2" name="a" checked/>
<input type="checkbox" value="3" name="a"/>
<input type="button" value="全选" onclick="alert( SCheckBox('form_a','a') )"/>
</form>
**************/
function SCheckBox(_formName,_checkboxName){
var selflag = {'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);
}
};
}else if(_scheckbox.checked){
selflag.checked++;
selflag.cvalues.push(_scheckbox.value);
}
if(selflag.checked){
return selflag;
}
}
return false;
}
//如果控件值=原来值则清空
function clearInput(input){
if(input.value == input.defaultValue){
input.value = "";
}
}
/***************表单操作结束**********/

/**************/
//收藏到书签.(兼容IE和FF)。
function addBookmark(title,url) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( document.all ) {
window.external.AddFavorite( url, title);
} else if( window.opera && window.print ) {
return true;
}
}
/**************
函数 : 文本框得到与失去焦点 操作。
这个方法经常在文本框搜索的时候出现。
文本里显示 “ 搜索 ”,然后当用户鼠标点击此文本,
文本框内容清空。如果用户没填写内容,那么文本的值又复原。
如果填写了,就显示用户填写的。
用法:
<input type="" value="关键字搜索" name="a" onfocus="clearTxt('a','关键字搜索')" onblur="fillTxt('a','关键字搜索')"/>
<input type="text" value="test" name="test" />
**************/
function clearTxt(id,txt) {
if (document.getElementById(id).value == txt)
document.getElementById(id).value="" ;
return ;
}
function fillTxt(id,txt) {
if ( document.getElementById(id).value == "" )
document.getElementById(id).value=txt;
return ;
}

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

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

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

/*********
验证是否是数字
**********/
function checkIsInteger(str)
{
//如果为空,则通过校验
if(str == "")
return true;
if(/^(\-?)(\d+)$/.test(str))
return true;
else
return false;
}
方便使用js的朋友,把下面的函数找到你想要的功能函数,复制部分判断输入文本是否为身份证号码,如为不正确则提示
/*------------------------------------------------------------
判断输入文本是否为身份证号码,如为不正确则提示
text-------输入的身份证号码
使用例子onBlur="isPid(this)"
------------------------------------------------------------*/
function isPid(text)
{
var pid=text.value.Trim();
var temp="0123456789";
var temp1="0123456789xX";
if(pid!=""){
if(pid.length==15)
{
for(j=0; j<15; j++ )
{
var ch = pid.charAt(j);
if(temp.indexOf(ch)==-1)
{
alert("请输入正确的身份证号码!");
text.focus();
break;
}
}
}
else if(pid.length==18)
{
for(j=0; j<pid.length-1; j++ )
{
var ch = pid.charAt(j);
if(temp.indexOf(ch)==-1)
{
alert("请输入正确的身份证号码!");
text.focus();
break;
}
}
var ch1 = 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)
------------------------------------------------------------*/
function checkPassword(text,text1)
{
var newpass=text.value.Trim();
var newpass1=text1.value.Trim();
if(newpass!=newpass1){
alert("两次输入新密码不一致!");
text.focus();
return true;
}
}

/**//*------------------------------------------------------------
判断是否包含非法字符,如含非法字符则提示
text-------输入文本
addtemp----除英文和数字外还可包含的字符
name-------提示的名字
include----提示中不允许包含的字符
使用例子onBlur="compareTwoDate(this,'@_','邮件','%*$')"
------------------------------------------------------------*/
function isChar(text,addtemp,name,include)
{
var temp="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+addtemp;
for(j=0; j<text.value.length; j++ )
{
var ch = text.value.Trim().charAt(j);
if(temp.indexOf(ch)==-1)
{
alert(name+"中不允许包含'"+include+"'等字符!");
text.focus();
break;
}
}
}
/**//*------------------------------------------------------------
判断输入的是否为电子邮件,如含非法字符则提示
text-------输入的电子邮件
使用例子onBlur="isEmail(this)"
------------------------------------------------------------*/
function isEmail(text)
{
var email=text.value.Trim();
var m=email.indexOf("@");
var n=email.indexOf(".");
if(email!="")
{
if(m<1||m>email.length-3)
{
alert("请输入正确的电子邮件格式!");
text.focus();
return true;
}
else if(n<m+2||n>email.length-2)
{
alert("请输入正确的电子邮件格式!");
text.focus();
return true;
}
}
}
/**//*------------------------------------------------------------
判断输入文本是否为空,如为空则提示
text-------输入文本
使用例子onBlur="isNull(this,'姓名')"
------------------------------------------------------------*/
function isNull(text,name)
{
if(text.value.Trim()==null||text.value.Trim()=="")
{
alert(name+"不能为空!");
text.focus();
return true;
}
}
//允许被框架
function enableFrame(){
if (top.location == self.location){
alert("该操作被管理员禁止");
document.execCommand("stop");
}
}
//禁止被框架
function disableFrame(obj){
if(top.location != self.location){
window.open(obj);
}
}

//根据ID控制层的隐藏或者展开
function show_hide(obj){
if($(obj).style.display == "none"){
$(obj).style.display = "";
}else{
$(obj).style.display = "none";
}
}
/*****屏幕*******************/
//调用方法:
//WinPage.getPageWidth
//WinPage.getBody().width
var WinPage = {
getPageWidth: function()
{
return document.body.scrollWidth || document.documentElement.scrollWidth || 0;
},
getPageHeight: function()
{
return document.body.scrollHeight || document.documentElement.scrollHeight || 0;
},
getBodyWidth: function()
{
return document.body.clientWidth || document.documentElement.clientWidth || 0;
},
getBodyHeight: function()
{
return document.documentElement.clientHeight || document.body.clientHeight || 0;
},
getBodyLeft: function()
{
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
},
getBodyTop: function()
{
return window.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()
{
return window.screen.width;
},
getScreenHeight: function()
{
return window.screen.height;
}
};
//测试浏览器类型//
var Browser = new Object();
Browser.ua = window.navigator.userAgent.toLowerCase();
Browser.ie = /msie/.test(Browser.ua);
Browser.moz = /gecko/.test(Browser.ua);
/****************/
//------------------用于载入一个文件-------------//
var JsLoader = {
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();
}
};
}
else if (Browser.moz)
{
_script.onload = function()
{
fCallback();
};
}
else
{
fCallback();
}
}
};
//实现一个StringBuffer
// var sb = new StringBuffer();
//sb.append("<table border='1'>");
//sb.append("<tr><td>A</td><td>B</td></tr>");
//sb.append("</table>")
//document.write(sb.toString());
function StringBuffer() {
this._strings_ = new Array;
}
StringBuffer.prototype.append = function(str) {
this._strings_.push(str);
}
StringBuffer.prototype.toString = function() {
return this._strings_.join("");
}
StringBuffer.prototype.reset= function() {
this._strings_ = new Array;
}