javascript惯用函数总汇
javascript常用函数总汇
1.document.write(""); 输出语句 2.JS中的注释为// 3.传统的HTML文档顺序是: document->html->(head,body) 4.一个浏览器窗口中的DOM顺序是: window->(navigator,screen,history,location,document) 5.得到表单中元素的名称和值: document.getElementById("表单中元素的ID号").name(或value) 6.一个小写转大写的JS: document.getElementById("output").value=document.getElementById("input").value.toUpperCase(); 7.JS中的值类型: String,Number,Boolean,Null,Object,Function 8.JS中的字符型转换成数值型: parseInt(),parseFloat() 9.JS中的数字转换成字符型: ("" 变量) 10.JS中的取字符串长度是: (length) 11.JS中的字符与字符相连接使用+号. 12.JS中的比较操作符有: ==等于,!=不等于,>,>=,<.<= 13.JS中声明变量使用: var来进行声明 14.JS中的判断语句结构: if(condition){}else{} 15.JS中的循环结构: for([initial expression];[condition];[upadte expression]) {inside loop} 16.循环中止的命令是: break 17.JS中的函数定义: function functionName([parameter],…){statement[s]} 18.当文件中出现多个form表单时.可以用document.forms[0],document.forms[1]来代替. 19.窗口: 打开窗口window.open(), 关闭一个窗口:window.close(), 窗口本身:self 20.状态栏的设置: window.status="字符"; 21.弹出提示信息: window.alert("字符"); 22.弹出确认框: window.confirm(); 23.弹出输入提示框: window.prompt(); 24.指定当前显示链接的位置: window.location.href="URL" 25.取出窗体中的所有表单的数量: document.forms.length 26.关闭文档的输出流: document.close(); 27.字符串追加连接符: = 28.创建一个文档元素: document.createElement(),document.createTextNode() 29.得到元素的方法: document.getElementById() 30.设置表单中所有文本型的成员的值为空: var form = window.document.forms[0] for (var i = 0; i<form.elements.length;i ){ if (form.elements.type == "text"){ form.elements.value = ""; } } 31.复选按钮在JS中判断是否选中: document.forms[0].checkThis.checked (checked属性代表为是否选中返回TRUE或FALSE) 32.单选按钮组(单选按钮的名称必须相同): 取单选按钮组的长度document.forms[0].groupName.length 33.单选按钮组判断是否被选中也是用checked. 34.下拉列表框的值: document.forms[0].selectName.options[n].value (n有时用下拉列表框名称加上.selectedIndex来确定被选中的值) 35.字符串的定义: var myString = new String("This is lightsword"); 36.字符串转成大写: string.toUpperCase(); 字符串转成小写:string.toLowerCase(); 37.返回字符串2在字符串1中出现的位置: String1.indexOf("String2")!=-1则说明没找到. 38.取字符串中指定位置的一个字符: StringA.charAt(9); 39.取出字符串中指定起点和终点的子字符串: stringA.substring(2,6); 40.数学函数: Math.PI(返回圆周率),Math.SQRT2(返回开方),Math.max(value1,value2)返回两个数中的 最在值,Math.pow(value1,10)返回value1的十次方,Math.round(value1)四舍五入函数, Math.floor(Math.random()*(n 1))返回随机数 41.定义日期型变量: var today = new Date(); 42.日期函数列表: dateObj.getTime()得到时间,dateObj.getYear()得到年份,dateObj.getFullYear()得到四位的年份, dateObj.getMonth()得到月份,dateObj.getDate()得到日,dateObj.getDay()得到日期几, dateObj.getHours()得到小时,dateObj.getMinutes()得到分,dateObj.getSeconds()得到秒, dateObj.setTime(value)设置时间,dateObj.setYear(val)设置年, dateObj.setMonth(val)设置月,dateObj.setDate(val)设置日, dateObj.setDay(val)设置星期几,dateObj.setHours设置小时,dateObj.setMinutes(val)设置分, dateObj.setSeconds(val)设置秒 [注意:此日期时间从0开始计] 43.FRAME的表示方式: [window.]frames[n].ObjFuncVarName,frames["frameName"].ObjFuncVarName,frameName.ObjFuncVarName 44.parent代表父亲对象,top代表最顶端对象 45.打开子窗口的父窗口为:opener 46.表示当前所属的位置:this 47.当在超链接中调用JS函数时用:(javascript :)来开头后面加函数名 48.在老的浏览器中不执行此JS:<!– //–> 49.引用一个文件式的JS:<script type="text/javascript" src="aaa.js"></script> 50.指定在不支持脚本的浏览器显示的HTML:<noscript></noscript> 51.当超链和onCLICK事件都有时,则老版本的浏览器转向a.html,否则转向b.html. 例:<a href="a.html" onclick="location.href='b.html';return false">dfsadf</a> 52.JS的内建对象有: Array,Boolean,Date,Error,EvalError, Function,Math,Number,Object,RangeError,ReferenceError, RegExp,String,SyntaxError,TypeError,URIError 53.JS中的换行:\n 54.窗口全屏大小: <script>function fullScreen(){ this.moveTo(0,0);this.outerWidth=screen.availWidth; this.outerHeight=screen.availHeight;}window.maximize=fullScreen;</script> 55.JS中的all代表其下层的全部元素 56.JS中的焦点顺序:document.getElementByid("表单元素").tabIndex = 1 57.innerHTML的值是表单元素的值: 如<p id="para">"how are <em>you</em>"</p>,则innerHTML的值就是:how are <em>you</em> 58.innerTEXT的值和上面的一样,只不过不会把<em>这种标记显示出来. 59.contentEditable可设置元素是否可被修改,isContentEditable返回是否可修改的状态. 60.isDisabled判断是否为禁止状态.disabled设置禁止状态 61.length取得长度,返回整型数值 62.addBehavior()是一种JS调用的外部函数文件其扩展名为.htc 63.window.focus()使当前的窗口在所有窗口之前. 64.blur()指失去焦点.与FOCUS()相反. 65.select()指元素为选中状态. 66.防止用户对文本框中输入文本: onfocus="this.blur()" 67.取出该元素在页面中出现的数量: document.all.tags("div(或其它HTML标记符)").length 68.JS中分为两种窗体输出:模态和非模态. window.showModaldialog(),window.showModeless() 69.状态栏文字的设置: window.status='文字',默认的状态栏文字设置:window.defaultStatus = '文字.'; 70.添加到收藏夹: external.AddFavorite("http://www.dannyg.com";,"jaskdlf"); 71.JS中遇到脚本错误时不做任何操作: window.onerror = doNothing; 指定错误句柄的语法为:window.onerror = handleError; 72.JS中指定当前打开窗口的父窗口: window.opener,支持opener.opener…的多重继续. 73.JS中的self指的是当前的窗口 74.JS中状态栏显示内容:window.status="内容" 75.JS中的top指的是框架集中最顶层的框架 76.JS中关闭当前的窗口:window.close(); 77.JS中提出是否确认的框:if(confirm("Are you sure?")){alert("ok");}else{alert("Not Ok");} 78.JS中的窗口重定向:window.navigate("http://www.sina.com.cn";); 79.JS中的打印:window.print() 80.JS中的提示输入框:window.prompt("message","defaultReply"); 81.JS中的窗口滚动条:window.scroll(x,y) 82.JS中的窗口滚动到位置:window.scrollby 83.JS中设置时间间隔:setInterval("expr",msecDelay)或setInterval(funcRef,msecDelay)或setTimeout 84.JS中的模态显示在IE4 行,在NN中不行:showModalDialog("URL"[,arguments][,features]); 85.JS中的退出之前使用的句柄: function verifyClose(){event.returnValue="we really like you and hope you will stay longer.";}} window.=verifyClose; 86.当窗体第一次调用时使用的文件句柄:onload() 87.当窗体关闭时调用的文件句柄:onunload() 88.window.location的属性: protocol(http:),hostname(www.example.com),port(80),host(www.example.com:80), pathname("/a/a.html"),hash("#giantGizmo",指跳转到相应的锚记),href(全部的信息) 89.window.location.reload()刷新当前页面. 90.window.history.back()返回上一页,window.history.forward()返回下一页, window.history.go(返回第几页,也可以使用访问过的URL) 91.document.write()不换行的输出,document.writeln()换行输出 92.document.body.noWrap=true;防止链接文字折行. 93.变量名.charAt(第几位),取该变量的第几位的字符. 94."abc".charCodeAt(第几个),返回第几个字符的ASCii码值. 95.字符串连接:string.concat(string2),或用 =进行连接 96.变量.indexOf("字符",起始位置),返回第一个出现的位置(从0开始计算) 97.string.lastIndexOf(searchString[,startIndex])最后一次出现的位置. 98.string.match(regExpression),判断字符是否匹配. 99.string.replace(regExpression,replaceString)替换现有字符串. 100.string.split(分隔符)返回一个数组存储值. 101.string.substr(start[,length])取从第几位到指定长度的字符串. 102.string.toLowerCase()使字符串全部变为小写. 103.string.toUpperCase()使全部字符变为大写. 104.parseInt(string[,radix(代表进制)])强制转换成整型. 105.parseFloat(string[,radix])强制转换成浮点型. 106.isNaN(变量):测试是否为数值型. 107.定义常量的关键字:const,定义变量的关键字:var 教程:JavaScript就这么回事1-5 有些时候你精通一门语言,但是会发现你其实整天在和其它语言打交道,也许你以为这些微不足道,不至于影响你的开发进度,但恰恰是这些你不重视的东西会浪费你很多时间,我一直以为我早在几年前就已经精通JavaScript了,直到目前,我才越来越觉得JavaScript远比我想象的复杂和强大,我开始崇拜它,就像崇拜所有OOP语言一样~ 趁着节日的空隙,把有关JavaScript的方法和技巧整理下,让每个在为JavaScript而烦恼的人明白,JavaScript就这么回事!并希望JavaScript还可以成为你的朋友,让你豁然开朗,在项目中更好的应用~ 适合阅读范围:对JavaScript一无所知~离精通只差一步之遥的人 基础知识:HTML JavaScript就这么回事1:基础知识 1 创建脚本块 1: <script language=”JavaScript”> 2: JavaScript code goes here 3: </script> 2 隐藏脚本代码 1: <script language=”JavaScript”> 2: <!– 3: document.write(“Hello”); 4: // –> 5: </script> 在不支持JavaScript的浏览器中将不执行相关代码 3 浏览器不支持的时候显示 1: <noscript> 2: Hello to the non-JavaScript browser. 3: </noscript> 4 链接外部脚本文件 1: <script language=”JavaScript” src="/”filename.js"”></script> 5 注释脚本 1: // This is a comment 2: document.write(“Hello”); // This is a comment 3: /* 4: All of this 5: is a comment 6: */ 6 输出到浏览器 1: document.write(“<strong>Hello</strong>”); 7 定义变量 1: var myVariable = “some value”; 8 字符串相加 1: var myString = “String1” + “String2”; 9 字符串搜索 1: <script language=”JavaScript”> 2: <!– 3: var myVariable = “Hello there”; 4: var therePlace = myVariable.search(“there”); 5: document.write(therePlace); 6: // –> 7: </script> 10 字符串替换 1: thisVar.replace(“Monday”,”Friday”); 11 格式化字串 1: <script language=”JavaScript”> 2: <!– 3: var myVariable = “Hello there”; 4: document.write(myVariable.big() + “<br>”); 5: document.write(myVariable.blink() + “<br>”); 6: document.write(myVariable.bold() + “<br>”); 7: document.write(myVariable.fixed() + “<br>”); 8: document.write(myVariable.fontcolor(“red”) + “<br>”); 9: document.write(myVariable.fontsize(“18pt”) + “<br>”); 10: document.write(myVariable.italics() + “<br>”); 11: document.write(myVariable.small() + “<br>”); 12: document.write(myVariable.strike() + “<br>”); 13: document.write(myVariable.sub() + “<br>”); 14: document.write(myVariable.sup() + “<br>”); 15: document.write(myVariable.toLowerCase() + “<br>”); 16: document.write(myVariable.toUpperCase() + “<br>”); 17: 18: var firstString = “My String”; 19: var finalString = firstString.bold().toLowerCase().fontcolor(“red”); 20: // –> 21: </script> 12 创建数组 1: <script language=”JavaScript”> 2: <!– 3: var myArray = new Array(5); 4: myArray[0] = “First Entry”; 5: myArray[1] = “Second Entry”; 6: myArray[2] = “Third Entry”; 7: myArray[3] = “Fourth Entry”; 8: myArray[4] = “Fifth Entry”; 9: var anotherArray = new Array(“First Entry”,”Second Entry”,”Third Entry”,”Fourth Entry”,”Fifth Entry”); 10: // –> 11: </script> 13 数组排序 1: <script language=”JavaScript”> 2: <!– 3: var myArray = new Array(5); 4: myArray[0] = “z”; 5: myArray[1] = “c”; 6: myArray[2] = “d”; 7: myArray[3] = “a”; 8: myArray[4] = “q”; 9: document.write(myArray.sort()); 10: // –> 11: </script> 14 分割字符串 1: <script language=”JavaScript”> 2: <!– 3: var myVariable = “a,b,c,d”; 4: var stringArray = myVariable.split(“,”); 5: document.write(stringArray[0]); 6: document.write(stringArray[1]); 7: document.write(stringArray[2]); 8: document.write(stringArray[3]); 9: // –> 10: </script> 15 弹出警告信息 1: <script language=”JavaScript”> 2: <!– 3: window.alert(“Hello”); 4: // –> 5: </script> 16 弹出确认框 1: <script language=”JavaScript”> 2: <!– 3: var result = window.confirm(“Click OK to continue”); 4: // –> 5: </script> 17 定义函数 1: <script language=”JavaScript”> 2: <!– 3: function multiple(number1,number2) { 4: var result = number1 * number2; 5: return result; 6: } 7: // –> 8: </script> 18 调用JS函数 1: <a href=”#” onClick=”functionName()”>Link text</a> 2: <a href="/”javascript:functionName"()”>Link text</a> 19 在页面加载完成后执行函数 1: <body onLoad=”functionName();”> 2: Body of the page 3: </body> 20 条件判断 1: <script> 2: <!– 3: var userChoice = window.confirm(“Choose OK or Cancel”); 4: var result = (userChoice == true) ? “OK” : “Cancel”; 5: document.write(result); 6: // –> 7: </script> 21 指定次数循环 1: <script> 2: <!– 3: var myArray = new Array(3); 4: myArray[0] = “Item 0”; 5: myArray[1] = “Item 1”; 6: myArray[2] = “Item 2”; 7: for (i = 0; i < myArray.length; i++) { 8: document.write(myArray[i] + “<br>”); 9: } 10: // –> 11: </script> 22 设定将来执行 1: <script> 2: <!– 3: function hello() { 4: window.alert(“Hello”); 5: } 6: window.setTimeout(“hello()”,5000); 7: // –> 8: </script> 23 定时执行函数 1: <script> 2: <!– 3: function hello() { 4: window.alert(“Hello”); 5: window.setTimeout(“hello()”,5000); 6: } 7: window.setTimeout(“hello()”,5000); 8: // –> 9: </script> 24 取消定时执行 1: <script> 2: <!– 3: function hello() { 4: window.alert(“Hello”); 5: } 6: var myTimeout = window.setTimeout(“hello()”,5000); 7: window.clearTimeout(myTimeout); 8: // –> 9: </script> 25 在页面卸载时候执行函数 1: <body onUnload=”functionName();”> 2: Body of the page 3: </body> JavaScript就这么回事2:浏览器输出 26 访问document对象 1: <script language=”JavaScript”> 2: var myURL = document.URL; 3: window.alert(myURL); 4: </script> 27 动态输出HTML 1: <script language=”JavaScript”> 2: document.write(“<p>Here’s some information about this document:</p>”); 3: document.write(“<ul>”); 4: document.write(“<li>Referring Document: “ + document.referrer + “</li>”); 5: document.write(“<li>Domain: “ + document.domain + “</li>”); 6: document.write(“<li>URL: “ + document.URL + “</li>”); 7: document.write(“</ul>”); 8: </script> 28 输出换行 1: document.writeln(“<strong>a</strong>”); 2: document.writeln(“b”); 29 输出日期 1: <script language=”JavaScript”> 2: var thisDate = new Date(); 3: document.write(thisDate.toString()); 4: </script> 30 指定日期的时区 1: <script language=”JavaScript”> 2: var myOffset = -2; 3: var currentDate = new Date(); 4: var userOffset = currentDate.getTimezoneOffset()/60; 5: var timeZoneDifference = userOffset - myOffset; 6: currentDate.setHours(currentDate.getHours() + timeZoneDifference); 7: document.write(“The time and date in Central Europe is: “ + currentDate.toLocaleString()); 8: </script> 31 设置日期输出格式 1: <script language=”JavaScript”> 2: var thisDate = new Date(); 3: var thisTimeString = thisDate.getHours() + “:” + thisDate.getMinutes(); 4: var thisDateString = thisDate.getFullYear() + “/” + thisDate.getMonth() + “/” + thisDate.getDate(); 5: document.write(thisTimeString + “ on “ + thisDateString); 6: </script> 32 读取URL参数 1: <script language=”JavaScript”> 2: var urlParts = document.URL.split(“?”); 3: var parameterParts = urlParts[1].split(“&”); 4: for (i = 0; i < parameterParts.length; i++) { 5: var pairParts = parameterParts[i].split(“=”); 6: var pairName = pairParts[0]; 7: var pairValue = pairParts[1]; 8: document.write(pairName + “ :“ +pairValue ); 9: } 10: </script> 你还以为HTML是无状态的么? 33 打开一个新的document对象 1: <script language=”JavaScript”> 2: function newDocument() { 3: document.open(); 4: document.write(“<p>This is a New Document.</p>”); 5: document.close(); 6: } 7: </script> 34 页面跳转 1: <script language=”JavaScript”> 2: window.location = “http://www.velee.cn”; 3: </script> 35 添加网页加载进度窗口 1: <html> 2: <head> 3: <script language='javaScript'> 4: var placeHolder = window.open('holder.html','placeholder','width=200,height=200'); 5: </script> 6: <title>The Main Page</title> 7: </head> 8: <body onLoad='placeHolder.close()'> 9: <p>This is the main page</p> 10: </body> 11: </html> JavaScript就这么回事3:图像 36 读取图像属性 1: <img src="/”image1.jpg"” name=”myImage”> 2: <a href=”# ” onClick=”window.alert(document.myImage.width)”>Width</a> 3: 37 动态加载图像 1: <script language=”JavaScript”> 2: myImage = new Image; 3: myImage.src = “Tellers1.jpg”; 4: </script> 38 简单的图像替换 1: <script language=”JavaScript”> 2: rollImage = new Image; 3: rollImage.src = “rollImage1.jpg”; 4: defaultImage = new Image; 5: defaultImage.src = “image1.jpg”; 6: </script> 7: <a href="/”myUrl"” onMouseOver=”document.myImage.src = rollImage.src;” 8: onMouseOut=”document.myImage.src = defaultImage.src;”> 9: <img src="/”image1.jpg"” name=”myImage” width=100 height=100 border=0> 39 随机显示图像 1: <script language=”JavaScript”> 2: var imageList = new Array; 3: imageList[0] = “image1.jpg”; 4: imageList[1] = “image2.jpg”; 5: imageList[2] = “image3.jpg”; 6: imageList[3] = “image4.jpg”; 7: var imageChoice = Math.floor(Math.random() * imageList.length); 8: document.write(‘<img src=”’ + imageList[imageChoice] + ‘“>’); 9: </script> 40 函数实现的图像替换 1: <script language=”JavaScript”> 2: var source = 0; 3: var replacement = 1; 4: function createRollOver(originalImage,replacementImage) { 5: var imageArray = new Array; 6: imageArray[source] = new Image; 7: imageArray[source].src = originalImage; 8: imageArray[replacement] = new Image; 9: imageArray[replacement].src = replacementImage; 10: return imageArray; 11: } 12: var rollImage1 = createRollOver(“image1.jpg”,”rollImage1.jpg”); 13: </script> 14: <a href=”#” onMouseOver=”document.myImage1.src = rollImage1[replacement].src;” 15: onMouseOut=”document.myImage1.src = rollImage1[source].src;”> 16: <img src="/”image1.jpg"” width=100 name=”myImage1” border=0> 17: </a> 41 创建幻灯片 1: <script language=”JavaScript”> 2: var imageList = new Array; 3: imageList[0] = new Image; 4: imageList[0].src = “image1.jpg”; 5: imageList[1] = new Image; 6: imageList[1].src = “image2.jpg”; 7: imageList[2] = new Image; 8: imageList[2].src = “image3.jpg”; 9: imageList[3] = new Image; 10: imageList[3].src = “image4.jpg”; 11: function slideShow(imageNumber) { 12: document.slideShow.src = imageList[imageNumber].src; 13: imageNumber += 1; 14: if (imageNumber < imageList.length) { 15: window.setTimeout(“slideShow(“ + imageNumber + “)”,3000); 16: } 17: } 18: </script> 19: </head> 20: <body onLoad=”slideShow(0)”> 21: <img src="/”image1.jpg"” width=100 name=”slideShow”> 42 随机广告图片 1: <script language=”JavaScript”> 2: var imageList = new Array; 3: imageList[0] = “image1.jpg”; 4: imageList[1] = “image2.jpg”; 5: imageList[2] = “image3.jpg”; 6: imageList[3] = “image4.jpg”; 7: var urlList = new Array; 8: urlList[0] = “http://some.host/”; 9: urlList[1] = “http://another.host/”; 10: urlList[2] = “http://somewhere.else/”; 11: urlList[3] = “http://right.here/”; 12: var imageChoice = Math.floor(Math.random() * imageList.length); 13: document.write(‘<a href=”’ + urlList[imageChoice] + ‘“><img src=”’ + imageList[imageChoice] + ‘“></a>’); 14: </script> JavaScript就这么回事4:表单 还是先继续写完JS就这么回事系列吧~ 43 表单构成 1: <form method=”post” action=”target.html” name=”thisForm”> 2: <input type=”text” name=”myText”> 3: <select name=”mySelect”> 4: <option value=”1”>First Choice</option> 5: <option value=”2”>Second Choice</option> 6: </select> 7: <br> 8: <input type=”submit” value=”Submit Me”> 9: </form> 44 访问表单中的文本框内容 1: <form name=”myForm”> 2: <input type=”text” name=”myText”> 3: </form> 4: <a href='#' onClick='window.alert(document.myForm.myText.value);'>Check Text Field</a> 45 动态复制文本框内容 1: <form name=”myForm”> 2: Enter some Text: <input type=”text” name=”myText”><br> 3: Copy Text: <input type=”text” name=”copyText”> 4: </form> 5: <a href=”#” onClick=”document.myForm.copyText.value = 6: document.myForm.myText.value;”>Copy Text Field</a> 46 侦测文本框的变化 1: <form name=”myForm”> 2: Enter some Text: <input type=”text” name=”myText” onChange=”alert(this.value);”> 3: </form> 47 访问选中的Select 1: <form name=”myForm”> 2: <select name=”mySelect”> 3: <option value=”First Choice”>1</option> 4: <option value=”Second Choice”>2</option> 5: <option value=”Third Choice”>3</option> 6: </select> 7: </form> 8: <a href='#' onClick='alert(document.myForm.mySelect.value);'>Check Selection List</a> 48 动态增加Select项 1: <form name=”myForm”> 2: <select name=”mySelect”> 3: <option value=”First Choice”>1</option> 4: <option value=”Second Choice”>2</option> 5: </select> 6: </form> 7: <script language=”JavaScript”> 8: document.myForm.mySelect.length++; 9: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].text = “3”; 10: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].value = “Third Choice”; 11: </script> 49 验证表单字段 1: <script language=”JavaScript”> 2: function checkField(field) { 3: if (field.value == “”) { 4: window.alert(“You must enter a value in the field”); 5: field.focus(); 6: } 7: } 8: </script> 9: <form name=”myForm” action=”target.html”> 10: Text Field: <input type=”text” name=”myField”onBlur=”checkField(this)”> 11: <br><input type=”submit”> 12: </form> 50 验证Select项 1: function checkList(selection) { 2: if (selection.length == 0) { 3: window.alert(“You must make a selection from the list.”); 4: return false; 5: } 6: return true; 7: } 51 动态改变表单的action 1: <form name=”myForm” action=”login.html”> 2: Username: <input type=”text” name=”username”><br> 3: Password: <input type=”password” name=”password”><br> 4: <input type=”button” value=”Login” onClick=”this.form.submit();”> 5: <input type=”button” value=”Register” onClick=”this.form.action = ‘register.html’; this.form.submit();”> 6: <input type=”button” value=”Retrieve Password” onClick=”this.form.action = ‘password.html’; this.form.submit();”> 7: </form> 52 使用图像按钮 1: <form name=”myForm” action=”login.html”> 2: Username: <input type=”text” name=”username”><br> 3: Password: <input type=”password”name=”password”><br> 4: <input type=”image” src="/”login.gif"” value=”Login”> 5: </form> 6: 53 表单数据的加密 1: <SCRIPT LANGUAGE='JavaScript'> 2: <!– 3: function encrypt(item) { 4: var newItem = ''; 5: for (i=0; i < item.length; i++) { 6: newItem += item.charCodeAt(i) + '.'; 7: } 8: return newItem; 9: } 10: function encryptForm(myForm) { 11: for (i=0; i < myForm.elements.length; i++) { 12: myForm.elements[i].value = encrypt(myForm.elements[i].value); 13: } 14: } 15: 16: //–> 17: </SCRIPT> 18: <form name='myForm' onSubmit='encryptForm(this); window.alert(this.myField.value);'> 19: Enter Some Text: <input type=text name=myField><input type=submit> 20: </form> JavaScript就这么回事5:窗口和框架 54 改变浏览器状态栏文字提示 1: <script language=”JavaScript”> 2: window.status = “A new status message”; 3: </script> 55 弹出确认提示框 1: <script language=”JavaScript”> 2: var userChoice = window.confirm(“Click OK or Cancel”); 3: if (userChoice) { 4: document.write(“You chose OK”); 5: } else { 6: document.write(“You chose Cancel”); 7: } 8: </script> 56 提示输入 1: <script language=”JavaScript”> 2: var userName = window.prompt(“Please Enter Your Name”,”Enter Your Name Here”); 3: document.write(“Your Name is “ + userName); 4: </script> 57 打开一个新窗口 1: //打开一个名称为myNewWindow的浏览器新窗口 2: <script language=”JavaScript”> 3: window.open(“http://www.velee.cn”,”myNewWindow”); 4: </script> 58 设置新窗口的大小 1: <script language=”JavaScript”> 2: window.open(“http://www.velee.cn”,”myNewWindow”,'height=300,width=300'); 3: </script> 59 设置新窗口的位置 1: <script language=”JavaScript”> 2: window.open(“http://www.velee.cn”,”myNewWindow”,'height=300,width=300,left=200,screenX=200,top=100,screenY=100'); 3: </script> 60 是否显示工具栏和滚动栏 1: <script language=”JavaScript”> 2: window.open(“http: 61 是否可以缩放新窗口的大小 1: <script language=”JavaScript”> 2: window.open('http://www.velee.cn' , 'myNewWindow', 'resizable=yes' );</script> 62 加载一个新的文档到当前窗口 1: <a href='#' onClick='document.location = '125a.html';' >Open New Document</a> 63 设置页面的滚动位置 1: <script language=”JavaScript”> 2: if (document.all) { //如果是IE浏览器则使用scrollTop属性 3: document.body.scrollTop = 200; 4: } else { //如果是NetScape浏览器则使用pageYOffset属性 5: window.pageYOffset = 200; 6: }</script> 64 在IE中打开全屏窗口 1: <a href='#' onClick=”window.open('http://www.juxta.com/','newWindow','fullScreen=yes');”>Open a full-screen window</a> 65 新窗口和父窗口的操作 1: <script language=”JavaScript”> 2: //定义新窗口 3: var newWindow = window.open(“128a.html”,”newWindow”); 4: newWindow.close(); //在父窗口中关闭打开的新窗口 5: </script> 6: 在新窗口中关闭父窗口 7: window.opener.close() 66 往新窗口中写内容 1: <script language=”JavaScript”> 2: var newWindow = window.open(“”,”newWindow”); 3: newWindow.document.open(); 4: newWindow.document.write(“This is a new window”); 5: newWIndow.document.close(); 6: </script> 67 加载页面到框架页面 1: <frameset cols=”50%,*”> 2: <frame name=”frame1” src="/”135a.html"”> 3: <frame name=”frame2” src="/”about:blank"”> 4: </frameset> 5: 在frame1中加载frame2中的页面 6: parent.frame2.document.location = “135b.html”; 68 在框架页面之间共享脚本 如果在frame1中html文件中有个脚本 1: function doAlert() { 2: window.alert(“Frame 1 is loaded”); 3: } 那么在frame2中可以如此调用该方法 1: <body onLoad=”parent.frame1.doAlert();”> 2: This is frame 2. 3: </body> 69 数据公用 可以在框架页面定义数据项,使得该数据可以被多个框架中的页面公用 1: <script language=”JavaScript”> 2: var persistentVariable = “This is a persistent value”; 3: </script> 4: <frameset cols=”50%,*”> 5: <frame name=”frame1” src="/”138a.html"”> 6: <frame name=”frame2” src="/”138b.html"”> 7: </frameset> 这样在frame1和frame2中都可以使用变量persistentVariable 70 框架代码库 根据以上的一些思路,我们可以使用一个隐藏的框架页面来作为整个框架集的代码库 1: <frameset cols=”0,50%,*”> 2: <frame name=”codeFrame” src="/”140code.html"”> 3: <frame name=”frame1” src="/”140a.html"”> 4: <frame name=”frame2” src="/”140b.html"”> 5: </frameset> 教程:事半功倍系列之javascript From:向东IT博客 本文由经典论坛 邓永炎 整理 清华大学出版的《事半功倍系列 javascript》,本人照着书敲出来的,有些翻译了一下.前几年看了一下,最近无事,重新翻了翻,很有帮助.本书应该有光盘的,但学校的书,光盘不知在哪.希望对你学 javascript有帮助 第一章javascript简介 1.在地址栏输入javascript语句 Javascript:Document.write("显示文字") 2.将javascript嵌入 HTML文档 <script language=javascript> document.bgColor="blue" </script> 第二章 使用变量和数组 1.声明变量 <script language=javascripe> Var answer1,answer2,answer3,answer4; answer1=9; answer2=2.5 answer3="Milkey May" answer4=true </script> 2.使用整数 <script language=javascript> var decimalNum,hexadecimalNum,octalNum decimalNum=24 hexadecimalNum=0×24 octalNum=024 document.write("显示十进制数:"+ decimalNum+"<br>") document.write("显示十六进制数:"+ hexadecimalNum +"<br>") document.write("显示八进制数:"+ octalNum +"<br>") </script> 3.使用浮点数 <script language=javascript> var num1,num2,num3,num4 num1=1234567890000.0 num2=5.14e23 num3=0.0000123456 num4=6.0254e3-4 document.write("浮点数1:"+num1+"<br>") document.write("浮点数2:"+num2+"<br>") document.write("浮点数3:"+num3+"<br>") document.write("浮点数4:"+num4+"<br>") </script> 4.使用布尔值 <script language=javascript> var answer1,answer2 answer1=true answer2=false document.write("显示布尔1:"+answer1+"<br>") document.write("显示布尔2:"+answer2+"<br>") </script> 5.使用字符串 <script language=javascript> var str1,str2 str1="fdsgdg dsfdsf china" str2="武汉市广播电视大学" document.write("显示字符串1:"+str1+"<br>") document.write("显示字符串2:"+str2+"<br>") </script> 6.确定变量类型 <script> var answer1,answer2,answer3,answer4 answer1=9 answer2=2.5 answer3="milky may" answer4=true document.write("变量1的类型是:"+typeof answer1 +"<br>") document.write("变量2的类型是:"+typeof answer2 +"<br>") document.write("变量3的类型是:"+typeof answer3 +"<br>") document.write("变量4的类型是:"+typeof answer4 +"<br>") </script> 7.将字符串转换成数字 <script> var str1="31 days in january" var int1=parseInt(str1) document.write("str1的数据类型是 :"+typeof str1+"<br>") document.write("int1的数据类型是 :"+typeof int1+"<br>") </script> 8.将数字转换成字符串 <script> var int1=256 var str1=""+int1 document.write("str1的数据类型是 :"+typeof str1+"<br>") document.write("int1的数据类型是 :"+typeof int1+"<br>") </script> 9.声明数组 <script> array=new Array(5) array[0]=1 array[1]=3 array[2]=5 array[3]=7 array[4]=11 document.write("数组是:"+array[0]+" "+array[1]+" "+array[2]+" "+array[3]+" "+array[4]) </script> 10.确定数组元素的个数 <script> array=new Array(5) array[0]=1 array[1]=3 array[2]=5 array[3]=7 array[4]=11 document.write("数组是:"+array[0]+" "+array[1]+" "+array[2]+" "+array[3]+" "+array[4]+"<br>") document.write("数组的元素个数是"+array.length) </script> 11.将数组转换为字符串 <script> array=new Array() array[0]="dark" array[1]="apple" array[2]="nebula" array[3]="water" str1=array.join() str2=array.join(" ") document.write(str1+"<br>") document.write(str2) </script> 12.对数组排序 <script> array=new Array() array[0]="dark" array[1]="apple" array[2]="nebula" array[3]="water" str1=array.sort() document.write(str1+"<br>") </script> 第三章 创建表达式 1.使用算术运算符 <script> var1=12 var2=10 varadd=var1+var2 varsub=var1-var2 varmult=var1*var2 vardiv=var1/var2 varmod=var1%var2 document.write("数据1是:"+var1+"<br>") document.write("数据2是:"+var2+"<br>") document.write("数据相加是:"+varadd+"<br>") document.write("数据相减是:"+varsub+"<br>") document.write("数据相乘是:"+varmult+"<br>") document.write("数据相除是:"+vardiv+"<br>") document.write("数据相除取余数是:"+varmod+"<br>") </script> 2.递增变量和递减变量 <script> days=1 document.write("输出变量"+days+"<br>") days++ document.write("递增后变量变为:"+days) </script> 3.创建比较表达式 <script> daysofmonth=28 if(daysofmonth==28) month="february" document.write("days of month:"+daysofmonth+"<br>") document.write("month:"+month) </script> 4.创建逻辑表达式 <script> dayofmonth=28 if(dayofmonth==28 || dayofmonth==29) month="february" document.write("days of month:"+dayofmonth+"<br>") document.write("month:"+month) </script> 5.使用条件运算符 <script language="javascript"> stomach="hungry"; time="5:00"; (stomach=="hungry"&&time=="5:00") ? eat = "dinner":eat="a snack"; document.write("输出结果"+eat); </script> 6.识别数字 <script> var1=24; (isNaN(var1))?document.write("变量var1"+var1+"不是数字"):Document.write("变量var1"+var1+"是数字") </script> 第四章 控制程序流程 1.使用IF –Else语句 <script> month="december" date=25 if(month=="december" && date==25) document.write("今天是圣诞节,商店关门") else document.write("欢迎,您来商店购物") </script> 2.使用for 循环 <script> for (count=1;count<=10;count++) document.write("输出第"+count+"句"+"<br>") </script> 3.使用while循环 <script> count=1 while(count<=15){ document.write("输出第"+count+"句" +"<br>") count++} </script> 4.中断循环 <script> count=1 while(count<=15){ count++ if(count==8) break; document.write("输出第"+count+"句"+"<br>")} </script> 5.继续循环 <script> count=1 while(count<=15){ count++ if(count==8) continue; document.write("输出第"+count+"句"+"<br>")} </script> 6.使用javascript定时器 <script> function rabbit() {document.write("输出语句") } </script> <body onload=window.setTimeout(rabbit(),5000)> 7.设置定期间隔 <script> window.setInterval("document.form1.text2.value=document.form1.text1.value",3000) </script> <form name=form1> <input type=text name=text1><br> <input type=text name=text2><br> </form> 8.清除超时和间隔 <script> stop=window.setInterval("document.form1.text2.value=document.form1.text1.value",300) </script> <form name=form1> <input type=text name=text1><br> <input type=text name=text2><br> <input type=button name=button1 value=" 清除超时和间隔" onclick=clearInterval(stop)> </form> 第五章 使用函数 1.声明函数 <script> function quote() { document.write("输出语句") } </script> 2.调用函数 <script> function quote() { document.write("输出语句") } quote() </script> 3.了解全局变量和局部变量 任何不用 var关键字声明的变量都是全局变量,任何在函数外声明的变量都是全局变量 4.将参数传送给函数 <script> function f(item) {document.write("输出参数"+item+"<br>") } f("fgdfgd") f("参数二") </script> 5.从函数返回值 <script> function average(var1,var2,var3) {ave=(var1+var2+var3)/3; document.write("输出结果"); return ave; } document.write(average(34,56,78)) </script> 6.通过HTML链接调用函数 <script> function quote(){ document.write(" 输出字符串") } </script> <a href=javascript:quote()>通过HTML链接调用函数</a> <a href=javascript:Document.write("输出字符")> 通过HTML链接调用函数,直接写javascript语句</a> 第六章 处理事件 1.检查鼠标单击 <form name=form1> <input type=button name=button1 value=hello onclick=document.form1.button1.value='there'> </form> 2.检测双击 <form name=form1> <input type=button name=button1 value=hello onclick=document.form1.button1.value='你单击了按钮' ondblclick=document.form1.button1.value='你双击了该按钮'> </form> 3.创建悬停按钮 <img src=go.gif onmouseover=document.images[0].src='go2.gif' onmouseout= document.images[0].src='go.gif'> 4.检测按键 <form name=form1> <input type=text name=text1 value=hello onkeypress="if(window.event.keyCode=='100') document.form1.text1.value='你按了d键'"> </form> 5.设置焦点 <form name=form1> <input type=text name=text1 value=hello onfous=document.form1.text1.value='该文本框获得焦点' onblur=document.form1.text1.value='该文本框失去焦点'> </form> 6.检测下拉菜单选择 <form name=form1> <select name=select1 size=4 onChange=document.form1.text1.value=document.form1.select1.value> <option value="北京">北京</option> <option value="上海">上海</option> <option value="武汉">武汉</option> <option value="天津">天津</option> <option value="大连">大连</option> </select> <input tppe=text name=text1 value=hello> </form> 7.创建网页加载和卸载信息 <body onload=document.form1.text1.value='页面加载完毕' onunload=alert('再见,欢迎再来')> <form name=form1> <input type=text name=text1 value="页面正在加载 ……"> </form> 第七章 使用对象 1.理解对象\属性和方法 <body bgcolor="green"> <script> document.write("页面背景颜色是:"+document.bgColor) document.write("页面前景颜色是:"+document.fgColor) </script> 2.使用网页元素对象 <script> </script> <form name=form1> <textarea name=ta1>dfgfdgfdhfdhdfdfgdf</textarea> <input type=button value="选择文本" onclick=document.form1.ta1.select()> <input type=button value="显示文本" onclick=document.write(document.form1.ta1.value)> </form> 3.使用子对象 <form name=form1> <input type=text name=text1 value=hello> </form> <script> document.form1.text1.value="gdfgfd" </script> <form name=form1> <input type=radio name=radio1>男 <input type=radio name=radio2>女 </script> <script> document.form1.radio1.checked=true </script> 4.使用预定义对象 <script> str1="dgdfgdfgdfhf固定法固定法功夫攻打法" document.write(str1+"<br>") str2=str1.substr(5) document.write(str2+"<br>") document.write("输出圆的面积:"+Math.PI*Math.pow(5.0,2)) </script> 5.创建新对象 <script> today=new Date() document.write("今天是"+(today.getMonth()+1)+"月"+today.getDate()+"日"+"<br>") document.write("现在是:"+today.toLocaleString()) </script> 6.引用当前对象 <form name=form1> <input type=text name=text1 value="dgdgdfgfd" onclick=this.select()> </script> 7.查看对象属性 <script> for(prop in window) {document.write("window."+prop+"="+window[prop]+"<br>");} for(prop2 in location) {document.write("location."+prop2+"="+location[prop]+"<br>");} </script> 8.使用Array对象 <script> array=new Array(10) array[0]="bark" array[1]="apple" array[2]="nebula" array[3]="cookie" array[4]="technology" document.write("数组元素个数是"+array.Length+"<br>") document.write("用 join将数组合并"+array.join(" ")+"<br>") document.write(" 数组排序"+array.sort()) </script> 9.使用 image 对象 <img src=**.gif alt="图片提示…." border=10> <script> document.write("图片提示是:"+document.images[0].alt+"<br>") document.write("图片边框大小是:"+document.images[0].broder) </script> 10.预加载图像 <script> freddy=new Image() freddy.src=freddy.gif </script> <body onload=document.images[0].src=freddy.src> ,<img src="blank.gif"> </body> 11.改变图像 <img src=freddy.gif><br> <form name=form1> <input type=button name=button1 value="改变图像" onclickd=document.images[0].src=dudjp.gif> </form> 12.使用link和anchor对象 <a name=anchor1>锚点1<br> <a href=http://www.microsoft.com>Microsoft</a><br> <a href=http://www.sohu.com>sohu</a><br> <a href=http://www.sina.com.cn>sina</a><br> <script> document.write("本页面共有"+document.links.length+"链接"+"<br>") document.write("本页面共有"+document.anchors.length+"锚点"+"<br>") document.write("第一个链接协议是"+document.links[0].protocol+"<br>") document.write("第一个链接路径是"+document.links[0].pathnamel+"<br>") document.write("第一个链接href是"+document.links[0].hrefl+"<br>") </script> 13.改变链接 <a href =http://www.microsoft.com>link</a> <form name=form1> <input type=button name=button1 value="改变链接" onclick=document.links[0].href='http://www.sohu.com'> </form> 14.使用history对象 <form name=form1> <input type=button name=button1 value="向后返回2页" onclick=window.history.go(-2)> </form> 第八章 使用窗口 1.在浏览器的状态栏上显示文本 <body onload=window.status="欢迎光临我的站点"> <a href=http://www.sohu.com>sohu</a> </body> 2.改变背景色 <script> document.bgColor="orange" </script> 3.列举背景颜色 <body bgColor =green> <script> document.write("当前背景色是:"+document.bgColor) </script> </body> 4.改变文本和链接颜色 <script> document.bgColor="orange" document.fgColor="blue" document.linkColor="red" </script> <h2>看看这段文本颜色</h2> <a href=http://www.sohu.com>sohu</a> </body> 5.改变文档标题 <script> name="Mouse" document.title="welcome to "+name+"'s House" document.write(document.title) </script> 6.显示修改日期 <script> document.write("本页面最后修改时间是"+document.lastModified) </script> 7.查看当前文档的URL <script> document.write("本页面的URL:"+document.URL) </script> 8.查看引用页 <script> document.write("本页面的引用页是"+document.referrer) </script> 9.打开新的浏览器窗口 <script> window.open("*.htm","title","width=200,height=400,resizable=yes") </script> 10.关闭远程窗口 close.html: <script> document.write("正文") </script> <form name=form1> <input type=button name=button1va, , , lue="关闭" onclick=window.close()> </form> open.html <script> window.open("close.html","romote","width=200,height=400,resizable=yes") </script> 11.打印窗口 <script> document.write("正文") </script> <form name=form1> <input type=button value=打印 onclick=window.print()> </form> 12.移动窗口 <form name=form1> 水平方向<input type=text name=x value=20> 垂直方向<input type=text name=y value=50> <input type=button value="移动窗口到…"onclick=window.moveTo(document.form1.x.value,document.form1.y.value)> </form> <form name=form1> 水平方向<input type=text name=x value=20> 垂直方向<input type=text name=y value=50> <input type=button value="移动窗口"onclick=window.moveBy(document.form1.x.value,document.form1.y.value)> </form> 13.改变窗口大小 <form name=form1> 水平方向<input type=text name=x value=200> 垂直方向<input type=text name=y value=500> <input type=button value="改变窗口大小到….."onclick=window.resizeTo(document.form1.x.value,document.form1.y.value)> </form> <form name=form1> 水平方向<input type=text name=x value=200> 垂直方向<input type=text name=y value=500> <input type=button value="改变窗口大小"onclick=window.resizeBy(document.form1.x.value,document.form1.y.value)> </form> 14.用警告对话框通知用户 <script> window.alert("welcome") </script> 15.用提示对话框接受输入 <script> name=window.prompt("输入姓名","姓名") document.write(" 欢迎您:"+name+"来到这里") </script> 16.用确认对话框使用户做出决定 <script> like=window.confirm("你觉得好吗?") if(like==true) document.write("谢谢你的夸奖") else document.write("希望得到你的夸奖") </script> 第九章 使用字符串 1.使用字符串对象 <script> mystring="gdgdfgfddddaaaaaaaaaaaabbbbbbbbbbbbbbbbbvbhg.<br>" document.write(mystring) document.write(mystring.bold()) document.write(mystring.toUpperCase()) </script> 2.使用子字符串 <script> str1="fdsf 1111 gfdgfd dfdsf cccc dddd.<br>" document.write(str1) document.write(str1.substring(0,13)+"<br>") document.write(str1.substr (20,11)+"<br>") </script> 3.连接字符串 <script> str1="may you find" str2="peace,happiness and prosperity.<br>" document.write(str1+"<br>") document.write(str2) document.write(str1.concat(str2)) document.write(str1+=str2) </script> 4.格式化字符串变量 <script> str1="peace,happiness and prosperity.<br>" document.write(str1) document.write(str1.big()) document.write(str1.small()) document.write(str1.bold()) document.write(str1.italics()) document.write(str1.strike()) document.write(str1.fontsize(6)) document.write(str1.fontcolor(green)) </script> 5.创建锚和链接 <script> str1="this is the bigginning of the page.<br>" str2="….<br>" str3="this is the end of the page .<br>" str4="link to the start<br>" str5="link to the end<br>" document.write(str1.anchor("start")) for(i=0;i<10;i++) document.write(str2); document.write(str3.anchor("end")) document.write(str4.link("#start")) document.write(str5.link("#end")) </script> 6.确定字符串长度 <script> str1="this is the bigginning of the page." document.write(str1+"<br>") document.write( "字符串的长度是:"+str1.length) document.write("字符串全部大写是;"+str1.toUpperCase()) document.write("字符串全部小写是;"+str1.toLowerCase()) </script> 7.在字符串内搜索 <script> str1="this is the end of the line.<br>" document.write(str1) document.write("字符end在字符串的位置是"+str1.search("end")) document.write("字符dog在字符串的位置是"+str1.search("dog")) </script> 8.定位字符串中的字符 <script> str1="spring is a time for flowers and trees and baby bunnles<br>" document.write(str1) document.write("the index for the second word ‘and' is"+str1.indexOf("and",30)) documednt.write("the last index of the word ‘and' is "+str1.lastIndexOf("and")) </script> 9.替换字符串中的文本 <script> str1="spring is a time for flowers and trees and baby bunnles<br>" document.write(str1) document .write(str1.replace("and",",")) </script> 10.字符串分离 <script> str1="spring is a time for flowers and trees and baby bunnles<br>" document.write(str1) str1array=str1.split(" ") document.write(str1array[0]+"<br>") document.write(str1array[1]+"<br>") document.write(str1array[2]+"<br>") document.write(str1array[3]+"<br>") </script> 第十章 使用日期和时间 1.使用Date对象 <script> cdate=new Date("august 2,1989 12:30:00") document.write(cdate) </script> 2.显示当地时间和日期 <script> cdate=new Date() document.write("当前时间是:"+cdate.toGMTString()+"<br>") document.write("日期和时间是:"+cdate.toLocaleString()) </script> 3.获得时间和日期值 <script> cdate=new Date() document.write("显示当前的星期"+cdate.getDay()+"<br>") document.write("显示当前的月份"+cdate.getMonth()+"<br>") document.write("显示当前的日期"+cdate.getDay()+"<br>") document.write("显示当前的年份"+cdate.getYear()+"<br>") document.write("显示当前的小时"+cdate.getHours()+"<br>") document.write("显示当前的分钟"+cdate.getMinutes()+"<br>") document.write("显示当前的秒"+cdate.getSeconds()+"<br>") </script> 4.设置时间和日期值 <script language=javascript> cdate=new Date("December 25,1984") document.write("显示日期"+cdate+"<br>") document.write("设置月份"+cdate.setMonth(10)+"<br>") document.write("设置日期"+cdate.setDate(23)+"<br>") document.write("设置年份"+cdate.setYear(2000)+"<br>") document.write("设置小时"+cdate.setHours(13)+"<br>"); document.write("设置分钟"+cdate.setMinutes(47)+"<br>"); document.write("设置秒"+cdate.setSeconds(23)+"<br>"); document.write("显示设置后的日期和时间"+cdate); </script> 第十一章 使用Math对象 1. 使用Math对象 <script language=javascript> </script> <form name=form1> 圆的半径:<input type=text name=rad><br> 圆的面积:<input type=text name=area><br> <input type=button name=button1 value=计算圆的面积 onclick=document.form1.area.value=document.form1.rad.value*document. form1.rad.value*Math.PI> </form> 2.生成随机数 <script> array1=new Array( "这是第1句", "这是第2句", "这是第3句", "这是第4句", "这是第5句", "这是第6句") RandomNo=Math.floor(array1.length*Math.random()) document.write("随机输出某一句"+"<br>"+array1[RandomNo]) </script> 3.使用平方根 <form name=form1> value:<input type=text name=va1><br> 平方根<input type=text name=sqrt><br> <input type=button name=button1 value=计算平方根 onclick="document.form1.sqrt.value=Math.sqrt(document.form1.va1.value)"> </form> 4.数字的舍入 <form name=form1> 输入<input type=text name=val><br> 舍入的结果<input type=text name=round><br> <input type=button name=button1 value=计算结果 onclick=document.form1.round.value=Math.round(document.form1.val.value)> </form> 5.乘方运算 <form name=form1> 底数<input type=text name=val><br> 指数<input type=text name=power><br> 幂<input type=text name=result><br> <input type=button name=button1 value=计算结果 onclick="document.form1.result.value=Math.pow (document.form1.val.value,document.form1.power.value)"> </form> 6.发现最小值和最大值 <form name=form1> 数字1<input type=text name=val1><br> 数字2<input type=text name=val2><br> 最小值<input type=text name=min><br> 最大值<input type=text name=max><br> 数字1<input type=button value=计算 onclick="document.form1.min.value=Math.min (document.form1.val1.value,document.form1.val2.value);document.form1. max.value= Math.max(document.form1.val1.value,document.form1.val2.value)"> </form> 第十二章 使用表单 1.使用文本框 <form name=form1> <input type=text value="information ,please"name=text1> </form> <script> document.write("表单text1类型是: "+document.form1.text1.type+"<br>") document.write("表单text1名称是: "+document.form1.text1.name+"<br>") document.write("表单text1值是: "+document.form1.text1.value+"<br>") document.write("表单text1大小是: "+document.form1.text1.size+"<br>") </script> <form name=form1> <input type=text name=text1 value=click here onfocus=document.form1.text1.select()> </form> 2.使用密码框 <form name=form1> <input type=password name=pw1 value=daylight> </form> <script> document.write("表单pw1的类型:"+document.form1.pw1.type+"<br>") document.write("表单pw1的名称:"+document.form1.pw1.name+"<br>") document.write("表单pw1的值:"+document.form1.pw1.value+"<br>") document.write("表单pw1的大小:"+document.form1.pw1.size+"<br>") </script> 3.使用隐藏字段 <form name=form1> <input type=hidden name=hid1 value=piece of eight> </form> <script> document.write("表单hid1的类型:"+document.form1.hid1.type+"<br>") document.write("表单hid1的名称:"+document.form1.hid1.name+"<br>") document.write("表单hid1的值:"+document.form1.hid1.value+"<br>") </script> 4.使用文本区域框 <form name=form1> <textarea name=ta1>how many grains of sand are there in the sahara desert?</textarea> </form> <script> document.write("表单ta1的类型:"+document.form1.ta1.type+"<br>") document.write("表单ta1的名称:"+document.form1.ta1.name+"<br>") document.write("表单ta1的值:"+document.form1.ta1.value+"<br>") document.write("表单ta1的横向宽度:"+document.form1.ta1.cols+"<br>") document.write("表单ta1的纵向宽度:"+document.form1.rows.value+"<br>") </script> 6.使用重置按钮 <form name=form1> <input type=reset name=reset1 value="rest form"> </form> <script> document.write("表单reset1的类型:"+document.form1.reset1.type+"<br>") document.write("表单reset1的名称:"+document.form1.reset1.name+"<br>") document.write("表单reset1的值:"+document.form1.reset1.value+"<br>") </script> 7.使用提交按钮 <form name=form1> <input type=submit name=submit1 value="submit form"> </form> <script> document.write("表单submit1的类型:"+document.form1.submit1.type+"<br>") document.write("表单submit1的名称:"+document.form1.submit1.name+"<br>") document.write("表单submit1的值:"+document.form1.submit1.value+"<br>") </script> 8.使用复选按钮 <form name=form1> <input type=checkbox name=cb1 >computer savvy? </form> <script> document.write("表单cb1的类型:"+document.form1.cb1.type+"<br>") document.write("表单cb1是否被选择?:"+document.form1.cb1.checked+"<br>") document.write("表单cb1的名称:"+document.form1.cb1.name+"<br>") </script> 9.使用单选按钮 <form name=form1> <input type=radio name=radio1>male <input type=radio name=radio1>female </form> <script> document.write("第一个按钮被选择"+document.form1.radio1[0].checked+"<br>") document.write("第二个按钮被选择"+document.form1.radio1[1].checked+"<br>") document.write("按钮的名称"+ document.form1.radio1[0].name+"<br>") document.write("按钮的个数"+document.form1.radio1.length) </script> 10.使用选择列表 <form name=form1> <select name=select1 size=4> <option name=option1 value=lon>london,England</option> <option name=option2 value=dub>Dublin,Ireland</option> </select> </form> <script> document.write("这个选择列表的名称"+document.form1.select1.name+"<br>") document.write("这个选择列表的长度"+document.form1.select1.length+"<br>") document.write("这个选择列表当前被选择的索引号"+document.form1.select1.selectedIndex+"<br>") document.write("这个选择列表的尺寸"+document.form1.select1.size+"<br>") </script> 11.验证表单的有效性 <script> function validate(){ if(document.form1.text1.value!='1'||'2'||'3'||'4'){ alert("请输入1~4的整数") } } </script> <form name=form1> 请输入1~4的整数: <input type=text name=text1 size=4 onchange=validate()> </form> 12.控制表单焦点 <form name=form1> <input type=text name=text1 value=where is you focus?><br> <input type=text name=text2 value=is there?><br> <input type=text name=text3 value=or maybe here?><br> <input type=button name=button1 value="text box #1" onclick=document.form1.text1.focus()><br> <input type=button name=button2 value="text box #2" onclick=document.form1.text2.focus()><br> <input type=button name=button3 value="text box #3" onclick=document.form1.text3.focus()><br> </form> 第十三章 使用分栏 第十四章 使用navigator 1.使用navigator对象 <script> document.write("navigator对象的属性"+"<br>") document.write("appcodename:"+navigator.appCodeName+"<br>") document.write("appname::"+navigator.appName+"<br>") document.write("appversion:"+navigator.appVersion+"<br>") document.write("platform:"+navigator.platform+"<br>") document.write("userAgent:"+navigator.userAgent+"<br>") </script> <script> document.write("navigator对象的方法"+"<br>") document.write("javaEnabled():"+navigator.javaEnabled()) </script> 2.检查用户的浏览器 <script> if(navigator.appName.indexOf("Microsoft")!=-1){ document.write("用户浏览器是微软的IE浏览器"+"<br>")} else if(navigator.appName.indexOf("Netscape")!=-1){ document.write("用户浏览器是netscape的netscape浏览器"+"<br>")} if(navigator.appVersion.indexOf("4.0")!=-1){ document.write("you are using a version 4.0compatible browser") } else{ document.write("this browser is not 4.0 compliant")} </script> 3.检测用户的操作系统 <script> if (navigator.platform.indexOf("win32")!=-1){ document.write("you are using a computer running windows 95 or highter")} else{ document.write("this computer is not running windows 95 or higher")} </script> 4.使用location对象 <script> document.write("location对象的属性"+"<br>") document.write("hash"+location.hash+"<br>") document.write("hostname"+location.hostname+"<br>") document.write("host"+location.host+"<br>") document.write("href"+location.href+"<br>") document.write("port"+location.port+"<br>") document.write("search"+location.search+"<br>") </script> 重新加载网页 <form name=form1> <input type=button name=button1 value=重新加载本页 onclick=location.reload> </form> 5.使用cookie <script> finction makecookie(){ if(!document.cookie){ name=prompt("请输入你的姓名"); document.cookie="name="+name+";";} } </script> <body onload=makecookie()> <script> function makecookie(){ if(!document.cookie){ name=prompt("请输入你的姓名") document.cookie="name="+name+";"; namestart=document.cookie.indexOf("="); nameend=document.cookieindexOf(";"); document.writeln("your name is:"+document.cookie.substring(namestart+1,nameend)+",br>") } } </script> 本文地址:http://www.bhcode.net/article_show.asp?showid=88