本人在学习和做项目中常用的js函数汇总.
一、用js做的表格动态增删查改
工具JavaScript:util.js
1
2//全选反选
3function checkAll(boxName) {
4 var checkBox = document.getElementsByName(boxName);
5 for (i = 0; i < checkBox.length; i++) {
6 var checked = checkBox[i].checked;
7 if (checked) {
8 checkBox[i].checked = false;
9 } else {
10 checkBox[i].checked = true;
11 }
12 }
13}
14//多选验证
15function multiCheck(idArray)
16{
17 //var idArray = document.getElementsByName(boxName);
18 var count = 0;
19 for(i=0;i<idArray.length;i++)
20 {
21 if(idArray[i].checked)
22 {
23 count++;
24 }
25 }
26 return count;
27}
28
29
30//回车切换焦点
31function toNext(next)
32{
33 if(event.keyCode==13)
34 {
35 next.focus();
36 }
37}
38
39//打开右键菜单
40function openShortCutMenu(oRow)
41{
42 // 选中当前行
43 SelectRow(oRow);
44 aOpenPopMenu("ShortCutMenu");
45 event.cancelBubble = true;
46 event.returnValue = false;
47}
48//关闭右键菜单
49function CloseShortCutMenu(){
50 aClosePopMenu("ShortCutMenu");
51}
52//显示右键菜单
53function aOpenPopMenu(MenuId){
54 if (document.all(MenuId)){
55 document.all(MenuId).style.left = event.clientX + document.body.scrollLeft;
56 document.all(MenuId).style.top = event.clientY + document.body.scrollTop;
57 document.all(MenuId).style.display = "";
58 }
59}
60//隐藏右键菜单
61function aClosePopMenu(MenuId){
62 if (document.all(MenuId)){
63 document.all(MenuId).style.display = "none";
64 }
65}
学生信息管理主页studentInfo.html
1<html>
2 <head>
3 <title>学生信息</title>
4 <script type="text/javascript" src="util.js"></script>
5 <script>
6 //显示更新学生信息模态窗体
7 function showDialog()
8 {
9 var result = window.showModalDialog("dialog.html",null,"dialogWidth=400px;dialogHeight=400px;");
10 if(result&&result.length!=0&&result[0]!="")
11 {
12 addRow(result);
13 }
14 }
15 //添加一行学生信息
16 function addRow(result)
17 {
18 var doc = window.listFrame.document;//内嵌框架的document对象
19 var tb = doc.getElementById("stuTable");//学生信息表格
20 var tbody = doc.getElementById("mytbody");
21 //创建新的行
22 var tr = doc.createElement("<tr onClick='SelectRow(this)' ondblclick='update();' oncontextmenu='openShortCutMenu(this)' title='右键修改'>");
23 //创建行的第一个单元格中的多选框
24 var check = document.createElement("<input name='idArray' type='checkbox'>");
25 var td = document.createElement("td");
26 td.appendChild(check);
27 tr.appendChild(td);
28 //将模式窗体传过来的值添加到新行中
29 for(i=0;i<result.length;i++)
30 {
31 var td = document.createElement("td");
32 td.appendChild(document.createTextNode(result[i]));
33 tr.appendChild(td);
34 }
35 tbody.appendChild(tr);
36 }
37 //删除学生信息
38 function delStudent()
39 {
40
41 var checks = window.listFrame.document.getElementsByName("idArray");
42 var count = multiCheck(checks);
43 if(count==0) {alert("未选中任何选项!"); return;}
44 if(window.confirm("确定要删除这"+count+"条信息吗?"))
45 {
46 while(count>0)
47 {
48 var tb = window.listFrame.document.getElementById("stuTable");
49 var checks = window.listFrame.document.getElementsByName("idArray");
50 for(i=0;i<checks.length;i++)
51 {
52 if(checks[i].checked)
53 {
54 tb.deleteRow(checks[i].parentElement.parentElement.rowIndex);
55 count--;
56 break;
57 }
58 }
59 }
60 }
61
62 }
63 //修改学生信息
64 function update()
65 {
66 var CurrRow = window.listFrame.CurrRow;
67 if(CurrRow&&CurrRow.cells.length>0)
68 {
69 var values = new Array();
70 for(i=0;i<CurrRow.cells.length-1;i++)
71 {
72 values[i] = CurrRow.cells[i+1].innerText;
73 }
74 values[values.length] = CurrRow;//将修改的当前行传给模式窗体进行修改
75 var result = window.showModalDialog("dialog.html",values,"dialogWidth=400px;dialogHeight=400px;");
76 }else
77 {
78 alert("请选中要修改的行");
79 }
80 }
81 </script>
82 </head>
83
84 <body bgcolor="#FFFFFF" text="#000000" onselectstart="return false;">
85 <table border="0" cellpadding="0" cellspacing="0" width="100%"
86 height="95%">
87 <tr>
88 <td width="100%" height="100%" valign="top">
89 <IFRAME width="100%" id="listFrame" height="100%" border=0
90 frameBorder=1 name="listFrame" src="list.html"></IFRAME>
91 </td>
92 </tr>
93 <tr>
94 <td width="100%" align="center" colspan="2">
95 <input class="btn_70" type="button" value="刷 新" id="btRefresh"
96 onclick="listFrame.location.reload();">
97   
98 <input class="btn_70" type="button" value="删 除" id="btDel"
99 onclick="delStudent();">
100   
101 <input class="btn_70" type="button" value="添 加" id="btAdd"
102 onclick="showDialog();">
103   
104 <input type="button" Class="btn_70" value="修 改" name="btModify"
105 onclick="update();">
106   
107 </td>
108 </tr>
109 </table>
110 </body>
111</html>
学生信息列表页面(list.html),此页面内嵌在studentInfo.html中
1<html>
2 <head>
3 <title>学生信息列表</title>
4 <script type="text/javascript" src="util.js"></script>
5 <script>
6 // 当前行对象变量
7 var CurrRow = null;
8 // 选定表格行函数
9 function SelectRow(row)
10 {
11 // 如果有曾选定过的行, 则恢复此行为未选定状态
12 if(CurrRow)
13 {
14 CurrRow.style.backgroundColor="";
15 }
16 // 设置新的选定行的状态
17 row.style.backgroundColor = '#D9F5FF';
18 // 前新的行赋给 当前行变量
19 CurrRow = row;
20 }
21 //更新学生信息
22 function update()
23 {
24 var values = new Array();
25 for(i=0;i<CurrRow.cells.length-1;i++)
26 {
27 values[i] = CurrRow.cells[i+1].innerText;
28 }
29 values[values.length] = CurrRow;//将修改的当前行传给模式窗体进行修改
30 var result = window.showModalDialog("dialog.html",values,"dialogWidth=400px;dialogHeight=400px;");
31 }
32 </script>
33 </head>
34
35 <body onmousedown="CloseShortCutMenu()">
36 <table border="1" width="100%" bordercolor="#666666" cellspacing="0" id="stuTable"
37 style="border-collapse: collapse" cellpadding="2" align="center">
38 <caption>07级学生信息列表</caption>
39 <tbody id="mytbody">
40 <tr class="th">
41 <td><input type="checkbox" onclick="checkAll('idArray');">[全选/反选]</td>
42 <td>学号</td>
43 <td>姓名</td>
44 <td>性别</td>
45 <td>年龄</td>
46 <td>学校</td>
47 <td>手机</td>
48 </tr>
49 <tr onClick="SelectRow(this)" ondblclick="update();" oncontextmenu="openShortCutMenu(this)" title="右键修改">
50 <td><input name="idArray" type="checkbox"></td>
51 <td>430901</td>
52 <td>hackiller</td>
53 <td>男</td>
54 <td>21</td>
55 <td>中南林业科技大学涉外学院</td>
56 <td>12345678901</td>
57 </tr>
58 </tbody>
59 </table>
60 <div id="ShortCutMenu" style="position: absolute; left: -200px; top: -200px; width: 120px; z-index: 999; display: none">
61 <table border="0" width="120" style="border-collapse: collapse; border: 2 outset #AEA67C" cellspacing="0" cellpadding="4" bgcolor="#EBF5FF">
62 <tr style="cursor: default" onmouseover="this.bgColor='#ADCFFF'" onmouseout="this.bgColor=''" onmousedown="update();">
63 <td width="90">修改</td>
64 </tr>
65 </table>
66 </div>
67 </body>
68</html>
更新学生信息对话框页面(dialog.html),用于添加和修改表格
1<html>
2 <head>
3 <title>更新学生信息</title>
4 <script type="text/javascript" src="util.js"></script>
5 <script>
6 var arg = window.dialogArguments;
7 function updateInfo()
8 {
9 var stuValues = getStuValues();
10 if(!arg)
11 {
12 window.returnValue = stuValues;
13 }else
14 {
15 for(i=0;i<stuValues.length;i++)
16 {
17 arg[arg.length-1].cells[i+1].innerText=stuValues[i];
18 }
19 }
20 window.close();
21 }
22 //取消更新
23 function cancle()
24 {
25 window.close();
26 }
27 //初始化
28 function init()
29 {
30 if(arg)
31 {
32 setStuValues(arg);
33 }
34 }
35 //获取学生信息
36 function getStuValues()
37 {
38 var tb = document.getElementById("stuInfoTb");
39 var stuValues = new Array(6);
40 for(i=0;i<6;i++)
41 {
42 //获取表格中每一行第2个单元格中的元素的值,即学生信息
43 stuValues[i] = tb.rows[i].cells[1].children[0].value;
44 }
45
46 var female = tb.rows[2].cells[1].children[1];
47 if(female.checked) stuValues[2]='女';
48 else stuValues[2]='男';
49 return stuValues;
50 }
51 //设置学生信息初始值
52 function setStuValues(stuValues)
53 {
54 var tb = document.getElementById("stuInfoTb");
55 for(i=0;i<6;i++)
56 {
57 //获取表格中每一行第2个单元格中的元素的值,即学生信息
58 var elem = tb.rows[i].cells[1].children[0];
59 elem.value = stuValues[i];
60 }
61 var female = tb.rows[2].cells[1].children[1];
62 if(stuValues[2]=='女') female.checked=true;
63 }
64 </script>
65 </head>
66
67 <body>
68 <table align="center" style="margin-top: 10%;" id="stuInfoTb">
69 <tr>
70 <td>学号</td>
71 <td><input type="text" id="stuID" name="stuID" onkeypress="toNext(stuName);"></td>
72 </tr>
73 <tr>
74 <td>姓名</td>
75 <td><input type="text" id="stuName" name="stuName" maxlength="20" onkeypress="toNext(stuAge);"></td>
76 </tr>
77 <tr>
78 <td>性别</td>
79 <td>
80 <input type="radio" id="male" name="stuSex" value="男" checked="checked">男
81
82 <input type="radio" id="female" name="stuSex" value="女">女
83 </td>
84 </tr>
85 <tr>
86 <td>年龄</td>
87 <td><input type="text" id="stuAge" name="stuAge" maxlength="2"
88 onkeypress="toNext(stuSchool);" onkeyup="this.value=this.value.replace(/\D/g,'');">
89 </td>
90 </tr>
91 <tr>
92 <td>学校</td>
93 <td><input type="text" id="stuSchool" name="stuSchool" maxlength="50" onkeypress="toNext(stuMobile);"></td>
94 </tr>
95 <tr>
96 <td>手机</td>
97 <td><input type="text" id="stuMobile" name="stuMobile" maxlength="50" onkeypress="if(event.keyCode==13) updateInfo();"></td>
98 </tr>
99 <tr align="center"><td colspan="2">
100 <input type="button" class="btn_70" value="确定" onclick="updateInfo();">
101
102 <input type="button" class="btn_70" value="取消" onclick="cancle();">
103 </td></tr>
104 </table>
105 <script>init();</script>
106 </body>
107</html>
二、在学习和做项目过程中写的JavaScript验证函数(正则表达式)
1//身份证合法性
2function isIdentity(new_num)
3{
4 var num = new_num;
5 var len = num.length ;
6 var re ;
7 if (len == 15)
8 {
9 if (isNaN(num)) {alert("输入的不是数字!"); return false;}
10 }
11 if (len == 15)
12 re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
13 else if (len == 18)
14 re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d|[X])$/);
15 else { alert("输入的数字位数不对!"); return false;}
16 var a = num.match(re);
17 if (a != null)
18 {
19 if (len==15)
20 {
21 var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]);
22 var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
23 }
24 else
25 {
26 var D = new Date(a[3]+"/"+a[4]+"/"+a[5]);
27 var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
28 }
29 if (!B) {alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false;}
30 }else
31 {
32 alert("输入的身份证号不对!");
33 return false;
34 }
35 return true;
36}
37//电子邮箱的合法性
38function checkemail(email)
39{
40 var myReg = /^([-_A-Za-z0-9\.]+)@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
41 if(!myReg.test( email ))
42 {
43 alert("请输入合法的电子邮件地址");
44 return false;
45 }
46 return true;
47}
48//验证邮政编码
49function checkPostcode(postcode)
50{
51 var reobj = new RegExp(/^\d+$/);
52 if(!reobj.test(postcode)||!postcode.length!=6)
53 {
54 alert("请输入正确的邮政编码");
55 return false;
56 }
57 return true;
58}
59//价格验证
60function checkPrice(price)
61{
62 var float = /^\d+(.){0,1}?\d{0,2}$/;//两位小数
63 var int = /^[1-9]\d*$/;//正整数
64 if(!float.test(price)&&!int.test(price))
65 {
66 alert("请输入正确的商品价格");
67 return false;
68 }
69 return true;
70}
71//验证上传图片类型
72function valiImgType(fileName)
73{
74 var extension = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();
75 if(extension!="jpg"&&extension!="gif")
76 {
77 alert("请选择jpg或gif格式的图片");
78 return false;
79 }
80 return true;
81}
82//验证是否为中文
83function iszhCN(name)
84{
85 var Expression=/[^\u4E00-\u9FA5]/;
86 var objExp=new RegExp(Expression);
87
88 if(!/^[\u4e00-\u9fa5]+$/.test(name))
89 {
90 alert("请输入汉字,验证未通过");
91 return false;
92 }
93 return true;
94}
95//验证IP地址
96function checkIP(sIPAddress)
97{
98 var exp=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
99 var reg = sIPAddress.match(exp);
100 var ErrMsg="你输入的是一个非法的IP地址段!\nIP段为::xxx.xxx.xxx.xxx(xxx为0-255)!"
101 if(reg==null)
102 {
103 alert(ErrMsg);
104 return false;
105 }
106 return true;
107}
三、在学习和做项目过程中写的常用JavaScript函数
1//四舍五入,保留valiNumber个小数;
2function round(number,valiNumber)
3{
4 document.write(number.toFixed(valiNumber));
5}
6
7// 判断字符串长度,一个中文按两个字符算
8function strlen(str)
9{
10 var len;
11 var i;
12 len = 0;
13 for (i=0;i<str.length;i++)
14 {
15 if (str.charCodeAt(i)>255) len+=2; else len++;
16 }
17 return len;
18}
四、用JavaScript限制html输入框为整数
1<!-- 第一种 -->
2<input onkeypress="return event.keyCode>=48&&event.keyCode<=57"
3 onpaste="var s=clipboardData.getData('text'); if(!/\D/.test(s)) value=s.replace(/^0*/,'');return false;"
4 onkeyup="if(/(^0+)/.test(value))value=value.replace(/^0*/, '')" />
5<!-- 第二种 -->
6<input type="text" onkeyup="this.value=this.value.replace(/\D/g,'');">