JavaScript 10分钟速成 (js-in-ten-minutes)

合集下载

js in用法

js in用法

js in用法==================JavaScript是一种强大的编程语言,被广泛应用于Web开发、桌面应用、移动应用等领域。

在JavaScript中,`in`是一个非常有用的运算符,它用于检查一个对象是否包含某个属性。

本文将介绍`in`运算符的用法。

一、基本概念------`in`运算符用于在对象中查找属性或方法。

如果对象包含该属性或方法,则返回`true`;否则返回`false`。

使用`in`运算符可以方便地检查对象是否包含特定的属性或方法,从而进行相应的操作。

二、语法----JavaScript中的`in`运算符的语法非常简单。

只需要将要检查的对象和要查找的属性或方法作为参数传递给`in`运算符即可。

```javascriptif (object in property) {// 执行操作}```或者使用简写形式:```javascriptif (property in object) {// 执行操作}```三、示例----下面是一个简单的示例,演示了如何使用`in`运算符检查一个对象是否包含特定的属性:```javascriptvar person = {name: "John",age: 30,city: "New York"};if ("name" in person) {console.log("The person object contains the name property.");} else {console.log("The person object does not contain the name property.");}```输出结果为:`The person object contains the name property.`,因为person对象确实包含name属性。

Javascript教程(重要)

Javascript教程(重要)

Javascript教程,javascript入门,学习笔记,Javascript Tutorials(源自网络)目录1.基本控件的使用2.让TextArea自动换行3.让TextArea支持Table键4.复制数据到剪贴板5.得到当前选中的文本6.客户端脚本的基本对象7.保护自己编写的HTML和脚本的方法8.IE地址栏前换成自己的图标9.可以在收藏夹中显示出你的图标10.关闭输入法11.直接查看源代码12.在Javascript中自定义一个对象(属性,方法)13.取得控件的绝对位置14.光标是停在文本框文字的最后15.判断上一页的来源16.最小化、最大化、关闭窗口17.检查一段字符串是否全由数字组成18.获得一个窗口的大小19.怎么判断是否是字符20.检测某个网站的链接速度21.各种样式的光标22.让TEXTAREA自适应文字的行数23.日期减去天数等于第二个日期24.选择了哪一个Radio25.获得本页url的request.servervariables("")集合26.ENTER键可以让光标移到下一个输入框28.引用其他网页29.常用的正则表达式30.弹出来必须关闭才能继续运行的提示对话框31.取得查询字符串,然后就生成成对的数组32.另类的onload函数33.取得IE的版本34.提交表单到不同地方35.判断是否是整数36.链接css文件和js文件37.引用框架的内容38.打开没有最大化按钮的窗口39.在页面上显示一个有边框的Frame40.判断日期1是不是大于日期241.常用的Javascript内建类的方法42.如何在另一个窗体对原来窗体进行操作43.层的隐藏与显示44.禁止右键45.得到当前显示器的分辨率46.定时运行特定代码47.得到本页网址48.保存当前页面的内容49.用模式窗体,打开一个参数获取窗体50.Web打印文档function document_onmousemove() {hello1.style.left=event.x+10;hello1.style.top=event.y+10;}</SCRIPT><返回>2.让TextArea自动换行使用TextArea的Wrap属性e of the following values:, lines are not wrapped.ap lines and place new line characters where the line wraps.p lines on the screen, but receive them as one line.ASP中手动换行用: replace(rs("A"),"</br>", VBCRLF)str=request.querystring("text1")str=Replace(str, Chr(32), " ")'把空格换成标志str=Replace(str, vbCrLf, "<br>")'把回车换行符换成<br>标志调出时再转过来就好了<返回>3.让TextArea支持Table键<SCRIPT LANGUAGE="JavaScript"><!--function testTab(){var sel = document.selection.createRange();var mytext= sel.text;var i,j,k;if (event.shiftKey && event.keyCode == 9){arr=mytext.split(String.fromCharCode(13,10))mytext=""for(k=0;k<arr.length;k++){for (j=1; j<=4;j++){if(arr[k].substr(0,1)=="\u0020"){arr[k]=arr[k].slice(1)}}mytext += arr[k] + ((k==(arr.length-1))? "" : String.fromCharCode(13,10));}with(sel){sel.text = mytext;collapse(true)moveEnd("character",0)moveStart("character",(mytext.length ) * -1)select()}window.event.cancelBubble = true;event.returnValue = false;return;}if (event.keyCode == 9){arr=mytext.split(String.fromCharCode(13,10))mytext=""for(j=0;j<arr.length;j++){mytext += "\u0020\u0020\u0020\u0020" + arr[j] + ((j==(arr.length-1))? "" : String.fromCharCode(13,10));}with(sel){sel.text = mytext;collapse(true)moveEnd("character",0)moveStart("character",(mytext.length -4) * -1)select()}window.event.cancelBubble = true;event.returnValue = false;return;}}//--></SCRIPT><返回>4.复制数据到剪贴板JM_cc(txt)window.clipboardData.setData("Text", txt);global.focus();document.execCommand('Paste');window.clipboardData.setData("Text", old);<返回>5.得到当前选中的文本var sel = document.selection.createRange();var mytext= sel.text; //当前选中的文本var e = event.srcElement; //设置文本为选中var r =e.createTextRange();r.moveStart('character',e.value.length);r.collapse(true);r.select();<返回>6.客户端脚本的基本对象<返回>7.保护自己编写的HTML和脚本的方法(1). oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键<table border oncontextmenu=return(false)><td>no</table> 可用于Table(2). <body onselectstart="return false"> 取消选取、防止复制(3). onpaste="return false" 不准粘贴(4). oncopy="return false;" oncut="return false;" 防止复制(5). 防止被人frame<SCRIPT LANGUAGE=JAVASCRIPT><!--if (top.location != self.location)top.location=self.location;// --></SCRIPT>(6). 永远都会带着框架<script language="JavaScript"><!--if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页 // --></script>(7).网页将不能被另存为<noscript><iframe src=*.html></iframe></noscript><返回>8.IE地址栏前换成自己的图标<link rel="Shortcut Icon" href="favicon.ico"><返回>9.可以在收藏夹中显示出你的图标<link rel="Bookmark" href="favicon.ico"><返回>10.关闭输入法<input style="ime-mode:disabled"><返回>11.直接查看源代码<input type=button value=查看网页源代码 onclick="window.location = 'view-source:'+'/'"><返回>12.在Javascript中定义一个对象(属性,方法)function pasta(grain, width, hasEgg) {this.grain = grain;this.width = width;this.hasEgg = hasEgg;this.toString = pastaToString;}function pastaToString() {return "Grain: " + this.grain + "\n" + "Width: " + this.width + "\n" + "Egg?: " +Boolean(this.hasEgg);}var P1=new pasta(3,3,false);<返回>13. 取得控件的绝对位置//Javascript<script language="Javascript">function getIE(e){var t=e.offsetTop;var l=e.offsetLeft;while(e=e.offsetParent){t+=e.offsetTop;l+=e.offsetLeft;}alert("top="+t+"\nleft="+l);}</script><返回>14. 光标是停在文本框文字的最后<script language="javascript">function cc(){var e = event.srcElement;var r =e.createTextRange();r.moveStart('character',e.value.length);r.collapse(true);r.select();}</script><input type=text name=text1 value="123" onfocus="cc()"> <返回>15. 判断上一页的来源asp:request.servervariables("HTTP_REFERER")javascript:document.referrer<返回>16. 最小化、最大化、关闭窗口<object id=hh1 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"> <param name="Command" value="Minimize"></object><object id=hh2 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"> <param name="Command" value="Maximize"></object><OBJECT id=hh3 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"> <PARAM NAME="Command" VALUE="Close"></OBJECT><input type=button value=最小化 onclick=hh1.Click()><input type=button value=最大化 onclick=hh2.Click()><input type=button value=关闭 onclick=hh3.Click()>本例适用于IE<返回>17. 检查一段字符串是否全由数字组成<script language="Javascript"><!--function checkNum(str){return str.match(/\D/)==null}// --></script><返回>18. 获得一个窗口的大小document.body.clientWidth,document.body.clientHeight<返回>19. 怎么判断是否是字符if (/[^\x00-\xff]/g.test(s))alert("含有汉字");elsealert("全是字符");<返回>20. 检测某个网站的链接速度把如下代码加入<body>区域中:<script language=Javascript>tim=1setInterval("tim++",100)b=1var autourl=new Array()autourl[1]=""autourl[2]=""autourl[3]=""autourl[4]=""autourl[5]=""function butt(){document.write("<form name=autof>")for(var i=1;i<autourl.length;i++)document.write("<input type=text name=txt"+i+" size=10 value=测试中……> =》<input type=text name=url"+i+" size=40> =》<input type=button value=GOonclick=window.open(this.form.url"+i+".value)><br/>")document.write("<input type=submit value=刷新></form>")}butt()function auto(url){document.forms[0]["url"+b].value=urlif(tim>200){document.forms[0]["txt"+b].value="链接超时"}else{document.forms[0]["txt"+b].value="时间"+tim/10+"秒"}b++}function run(){for(var i=1;i<autourl.length;i++)document.write("<img src=http://"+autourl[i]+"/"+Math.random()+" width=1 height=1 onerror=auto('http://"+autourl[i]+"')>")}run()</script><返回>21. 各种样式的光标auto :标准光标default :标准箭头hand :手形光标wait :等待光标text :I形光标vertical-text :水平I形光标no-drop :不可拖动光标not-allowed :无效光标help :?帮助光标all-scroll :三角方向标move :移动标crosshair :十字标e-resizen-resizenw-resizew-resizes-resizese-resizesw-resize<返回>22.让TEXTAREA自适应文字的行数<textarea rows=1 name=s1 cols=27onpropertychange="this.style.posHeight=this.scrollHeight"></textarea><返回>23. 日期减去天数等于第二个日期<script language=Javascript>function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")}cc("12/23/2002",2)</script><返回>24. 选择了哪一个Radio<HTML><script language="vbscript">function checkme()for each ob in radio1if ob.checked thenwindow.alert ob.valuenextend function</script><BODY><INPUT name="radio1" type="radio" value="style" checked>Style<INPUT name="radio1" type="radio" value="barcode">Barcode<INPUT type="button" value="check" onclick="checkme()"></BODY></HTML><返回>25.获得本页url的request.servervariables("")集合Response.Write "<TABLE border=1><!-- Table Header--><TR><TD><B>Variables</B></TD><TD><B>Value</B></TD></TR>"for each ob in Request.ServerVariablesResponse.Write "<TR><TD>"&ob&"</TD><TD>"&Request.ServerVariables(ob)&"</TD></TR>" nextResponse.Write "</TABLE>"<返回>26.ENTER键可以让光标移到下一个输入框<input onkeydown="if(event.keyCode==13)event.keyCode=9"><返回>28.引用其他网页<table width=100% border="0"><tr><td><script language="JavaScript"location="" id="nd91down"src="/js/new1-1.htm"></script></td><td><script language="JavaScript" location="" id="nd91down"src="/js/new1-2.htm"></script></td></tr></table><返回>29.常用的正则表达式匹配中文字符的正则表达式: [\u4e00-\u9fa5]匹配双字节字符(包括汉字在内):[^\x00-\xff]匹配空行的正则表达式:\n[\s| ]*\r匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/匹配首尾空格的正则表达式:(^\s*)|(\s*$)匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?(1)应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}(2)应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g, "");}(3)应用:利用正则表达式分解和转换IP地址function IP2V(ip) //IP地址转换成对应数值{re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式if(re.test(ip)){returnRegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1 }else{throw new Error("Not a valid IP address!")}}(4)应用:从URL地址中提取文件名的javascript程序s="/page1.htm";s=s.replace(/(.*\/){0,}([^\.]+).*/ig,"$2") ; //Page1.htm(5)应用:利用正则表达式限制网页表单里的文本框输入内容用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))"用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g, ''))"用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g, ''))"<返回>30.弹出来提示对话框window.showModalDialog(url);<返回>31.取得查询字符串,然后就生成成对的数组var argstr = window.top.location.search.substring(1,window.top.location.search.length);var args = argstr.split('&');<返回>32.另类的onload函数<SCRIPT FOR=window event=onload>try{Start();}catch (exception){}</script><返回>33.取得IE的版本var ieVer = parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf("MSIE ")+5, navigator.appVersion.length))var isIE6 = ieVer >= 6.0<返回>34.提交表单// aimForm 为表单名 aimPage为提交到的页//提交表单到新建的网页function SubmitFormToNewPage(aimForm,aimPage){ aimForm.method="POST";aimForm.target="_blank";aimForm.action=aimPage;aimForm.submit();}//在本地提交表单function SubmitFormToLocalPage(aimForm,aimPage){ aimForm.method="POST";aimForm.target="_self";aimForm.action=aimPage;aimForm.submit();}<返回>35.判断是否是整数function IsNum(s) //整数{if(s=="null"||s=="undefined"||s.length<1) return false;if(isNaN(parseInt(s)))return false;elseif((parseInt(s)+"").length!=s.length)return false;elsereturn true;}function IsNumber(JudgeNum){ //判断大于0的数 var JudgeStr=JudgeNum.toString();for (var i=0;i<JudgeStr.length;i++) {var oneChar=JudgeStr.charAt(i);if (oneChar<"0" || oneChar >"9"){return false;}}return true;}<返回>36.链接css文件和js文件<link rel="stylesheet" href="../css/style.css" type="text/css"><script language="javascript" src="../includes/jslib.js" ></script><返回>37.引用框架的内容window.top.frames["mainFrame"].location.href=s;在IFRAME标签中引用框架的内容parent.frames["mainFrame"].location.href在窗口中引用IFrame中的内容window.top.frames["mainFrame"].confFrame.location.href<返回>38.打开没有最大化按钮的窗口window.open("","","width=250,height=220,scrollbars=no,resizable=no,cent er=yes");<返回>39.在页面上显示一个有边框的Frame<fieldset style="width:500;height:100"><legend>标题</legend>具体内容</fieldset><返回>40.判断日期1是不是大于日期2function IsDate1AfterThanDate2(year1,month1,day1,year2,month2,day2){var iFrom=Date.parse(month1+"-"+day1+"-"+year1);var iTo=Date.parse(month2+"-"+day2+"-"+year2);if(iFrom>iTo)return true;elsereturn false;}function IsDate(year,month,day){if( (!IsNumber(year))||(year.length!=4))return false;if( (!IsNumber(month))||(month>12)||(month<1) )return false;if( (!IsNumber(day))||(day>31)||(day<1) )return false;var myDate=new Date();myDate.setFullYear(year,month-1,day);if (isNaN(myDate.getFullYear())){return false;}else{if( (myDate.getFullYear()!=year)||(myDate.getDate()!=day)||(myDate.getMonth()!=(m onth-1).toString()) )return false;}return true;}function IsNumber(JudgeNum){var JudgeStr=JudgeNum.toString();for (var i=0;i<JudgeStr.length;i++) {var oneChar=JudgeStr.charAt(i);if (oneChar<"0" || oneChar >"9"){return false;}}return true;}<返回>41.常用的Javascript内建类的方法对象方法或属性意义例子在打开的新窗体,用window.opener来访问原来窗体的对象。

JS实现十分钟倒计时代码实例

JS实现十分钟倒计时代码实例

JS实现⼗分钟倒计时代码实例编写JS倒计时代码需要⽤到很多JavaScript知识,⽐如:if函数,Math.floor,定时器setInterval等等,如有不清楚的⼩伙伴可以参考PHP中⽂⽹的相关⽂章,或者访问 JavaScript视频教程。

举例:10分钟考试倒计时,当时间仅剩五分钟时,提醒考试仅剩5分钟,时间结束时,提⽰考试结束。

具体代码如下:HTML部分:<body><div id="timer"></div><div id="warring"></div></body>JavaScript部分:<script type="text/javascript">var maxtime = 10 * 60; //function CountDown() {if (maxtime >= 0) {minutes = Math.floor(maxtime / 60);seconds = Math.floor(maxtime % 60);msg = "距离结束还有" + minutes + "分" + seconds + "秒";document.all["timer"].innerHTML = msg;if (maxtime == 5 * 60)alert("距离结束仅剩5分钟");--maxtime;} else{clearInterval(timer);alert("时间到,结束!");}}timer = setInterval("CountDown()", 1000);</script>JS⼗分钟倒计时代码的具体步骤:1、设置考试时长maxtime = 10 * 60秒,即10分钟2、⽤if函数判断,当maxtime⼤于等于零时,判断剩余分和秒3、再⽤if函数判断,当时间仅剩5分钟时,弹出提⽰:距离结束仅剩5分钟4、如果时间到,则清除定时器,提⽰:结束效果如图所⽰:。

js10秒钟倒计时

js10秒钟倒计时

js10秒钟倒计时第⼀个:<html><head><meta http-equiv="Content-Type"content="text/html; charset=gb2312"><title>counter</title><script language="javascript"type="text/JavaScript">function Counter(nMax,nInterval){this.maxTime=nMax;this.interval=nInterval;this.objId="timer";this.obj=null;this.num=this.maxTime;this.timer=null;this.start=function(){this.obj=document.getElementById(this.objId);if(this.num>0) setTimeout(this.run,this.interval*1000);};this.run=function(){if(myCounter.num>0){myCounter.num--;myCounter.obj.innerHTML=myCounter.num;myCounter.timer=setTimeout(myCounter.run,myCounter.interval*1000);}else clearTimeout(myCounter.timer);};this.show=function(){document.write("<span id="+this.objId+">"+this.num+"</span>");this.obj=document.getElementById(this.objId);//alert(this.obj.innerHTML);}}</script></head><body onload="myCounter.start();"><script language="JavaScript"type="text/JavaScript">var myCounter=new Counter(10,1);</script><p>现在剩下<script language="JavaScript"type="text/JavaScript">myCounter.show();</script>秒钟!</p>第⼆个:很中庸的倒计时,我⽤的这个请等待<span id="dd">10</span>秒<script type="text/javascript">function run(){var s = document.getElementById("dd");if(s.innerHTML == 0){window.location.href='';return false;}s.innerHTML = s.innerHTML * 1 - 1;}window.setInterval("run();", 1000);</script>第三个:毫秒级的,⽐较紧张:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"""><script type="text/javascript"><!--var duration=9900;var endTime = new Date().getTime() + duration + 100;function interval(){var n=(endTime-new Date().getTime())/1000;if(n<0) return;document.getElementById("timeout").innerHTML = n.toFixed(3);setTimeout(interval, 10);}window.onload=function(){setTimeout("window.location.href=''", duration);interval();}//--></script><html xmlns=""><head runat="server"><title>等待10秒</title></head><body><form id="form1"runat="server"><div>现在剩下 <span id="timeout">10.000</span> 秒后将⾃动跳转 </div> </form></body></html>。

javascript小技巧-js小技巧收集(转)每一项都是js中的小技巧,但十分的实用!

javascript小技巧-js小技巧收集(转)每一项都是js中的小技巧,但十分的实用!

javascript小技巧-js小技巧收集(转)每一项都是js中的小技巧,但十分的实用!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,Function8.JS中的字符型转换成数值型:parseInt(),parseFloat()9.JS中的数字转换成字符型:(""+变量) 10.JS中的取字符串长度是:(length) 11.JS中的字符与字符相连接使用+号. 12.JS中的比较操作符有:==等于,!=不等于,>,>=,<.<= 13.JS中声明变量使用:var来进行声明14.JS中的判断语句结构:if(condition){}else{} 15.JS中的循环结构:for([initial e-xpression];[condition];[upadte e-xpression]) {inside loop} 16.循环中止的命令是:break 17.JS中的函数定义:function functionName([parameter],...) 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.createT extNode() 29.得到元素的方法:document.getElementById() 30.设置表单中所有文本型的成员的值为空: var form = window.document.forms[0] for (var i = 0; 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: 50.指定在不支持脚本的浏览器显示的HTML: 51.当超链和onCLICK事件都有时,则老版本的浏览器转向a.html,否则转向 b.html.例:dfsadf 52.JS的内建对象有:Array,Boolean,Date,Error,EvalError,Function,Math,Number,Object,RangeError,Refere nceError,RegExp,String,SyntaxError,TypeError,URIError 53.JS中的换行:/n 54.窗口全屏大小: 55.JS中的all代表其下层的全部元素56.JS中的焦点顺序:document.getElementByid("表单元素").tabIndex = 1 57.innerHTML的值是表单元素的值:如"how are you" ,则innerHTML的值就是:how are you 58.innerTEXT的值和上面的一样,只不过不会把这种标记显示出来. 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(""t;,"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?"))else{alert("Not Ok");} 78.JS中的窗口重定向:window.navigate(""t;); 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.onbeforeunload=verifyClose; 86.当窗体第一次调用时使用的文件句柄:onload() 87.当窗体关闭时调用的文件句柄:onunload() 88.window.location的属性: protocol(http:),hostname(),port(80),host(:80),pathname("/a/a.h tml"),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开始计算) stIndexOf(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 --------------------------------------------------------------------------------------------------------------------------------javascript38种小技巧,推荐新手查看。

JavaScript 计时

JavaScript 计时

JavaScript 计时通过使用 JavaScript,我们有能力做到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后 立即执行。

我们称之为计时事件。

实例简单的计时 单击本例中的按钮后,会在 5 秒后弹出一个警告框。

<html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('5 秒!')",5000) } </script> </head> <body> <form> <input type="button" value="显示定时的警告框" onClick = "timedMsg()"> </form> <p>请点击上面的按钮。

警告框会在 5 秒后显示。

</p> </body> </html>另一个简单的计时 本例中的程序会执行 2 秒、4 秒和 6 秒的计时。

<html> <head> <script type="text/javascript"> function timedText() { var t1=setTimeout("document.getElementById('txt').value='2 秒'",2000) var t2=setTimeout("document.getElementById('txt').value='4 秒'",4000) var t3=setTimeout("document.getElementById('txt').value='6 秒'",6000) } </script> </head><body> <form> <input type="button" value="显示计时的文本" onClick="timedText()"> <input type="text" id="txt"> </form> <p>点击上面的按钮。

js入门教程

js入门教程

js入门教程JavaScript是一门广泛应用于网页开发的脚本语言。

在当前的Web开发环境中,JavaScript已经成为前端开发的核心技术之一。

本篇文章将为大家介绍JavaScript的入门教程,帮助初学者快速掌握这门语言。

首先,了解JavaScript的基础知识是非常重要的。

JavaScript是一种运行在浏览器中的解释型脚本语言,它能够实现网页的动态效果和交互功能。

与HTML和CSS不同,JavaScript能够对网页进行处理和操作,实现一些更加复杂的功能。

接下来,我们需要了解JavaScript的语法。

JavaScript的语法与其他编程语言类似,包括变量的声明和赋值、条件判断、循环等。

例如,通过使用var关键字可以声明一个变量,使用等号可以给变量赋值。

条件判断和循环可以使用if-else语句和for 循环等结构来实现。

另外,了解JavaScript的常用数据类型也是必不可少的。

JavaScript支持多种数据类型,包括字符串、数字、布尔、数组和对象等。

我们可以使用这些数据类型来存储和操作数据。

在学习JavaScript的过程中,我们还需要掌握如何操作DOM (Document Object Model)。

DOM是指网页中的文档对象模型,通过JavaScript我们可以通过操作DOM来实现网页中的动态效果。

例如,通过getElementById()方法可以获取网页中的元素,并对它们进行操作和修改。

同时,学习JavaScript的时候还需要掌握如何处理事件。

事件是指用户在网页上的行为触发的动作,例如点击按钮或者输入文本。

通过JavaScript可以对这些事件进行监听,并且执行相应的操作和函数。

最后,为了更好地学习JavaScript,我们可以使用一些工具和资源。

例如,可以使用浏览器的开发者工具来调试JavaScript 代码,以及使用在线的文档和教程来查找和学习新的知识。

综上所述,JavaScript是一门重要且实用的编程语言,尤其在网页开发中发挥着重要的作用。

javascript方法和技巧大全

javascript方法和技巧大全

javascript方法和技巧大全这篇介绍JavaScript方面的日志,我在是Clang上看到的。

作者介绍挺全面的,所以转载过来让感兴趣的朋友看一下。

呵呵~~~适合阅读范围:对JavaScript一无所知~离精通只差一步之遥的人基础知识:HTMLJavaScript就这么回事1:基础知识1 创建脚本块1: <script language=”JavaScript”>2: JavaScript code goes here3: </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 comment2: document.write(“Hello”); // This is a comment 3: /*4: All of this5: is a comment6: */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: doc ument.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.wr ite(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 page3: </body>20 条件判断1: <script>2: <!--3: var userChoice = window.confirm(“Choose OK or Cancel”); 4: var resu lt = (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 page3: </body>JavaScript就这么回事2:浏览器输出26 访问document对象1: <script language=”JavaScript”>2: var myURL = document.URL;3: window.alert(myURL);4: </script>27 动态输出HTML1: <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 = “/”;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: defaultIma ge.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.setTimeo ut(“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.my Form.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 访问选中的Select1: <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 F ield: <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 动态改变表单的action1: <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 = windo w.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(“/”,”myNewWindow”);4: </script>58 设置新窗口的大小1: <script language=”JavaScript”>2: window.open(“/”,”myNewWindow”,'height=300,width=300');3: </script>59 设置新窗口的位置1: <script language=”JavaScript”>2:window.open(“/”,”myNewWindow”,'height=300,width=300,left=200,scree nX=200,top=100,screenY=100');3: </script>60 是否显示工具栏和滚动栏1: <script language=”JavaScript”>2: window.open(“http:61 是否可以缩放新窗口的大小1: <script language=”JavaScript”>2: window.open('/' , '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('/','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 col s=”50%,*”>5: <frame name=”frame1” src="/”138a.html"”>6: <frame name=”frame2” src="/”138b.html"”>7: </frameset>这样在frame1和frame2中都可以使用变量persistentV ariable70 框架代码库根据以上的一些思路,我们可以使用一个隐藏的框架页面来作为整个框架集的代码库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>正在处理您的请求...lxs5i5j的专栏CSDN | 社区| 技术中心| BLOG首页| 我的首页| 个人档案| 联系作者| 聚合| 搜索| 登录16篇原创: 0篇翻译: 8篇转载: 2698次点击: 11个评论: 0个Trackbacks文章.net功能模块(RSS).net技巧(RSS)ajax(RSS)js收集(RSS)错误集(RSS)其它(RSS)收藏相册存档2007年02月(3)2007年01月(21)最近评论wuheng08:太谢谢redstonebupt:大哥对不怎么没有数据绑定那lovexiaomantou:辛苦了!greatwallmy:好东西呀!谢谢了Sandy945:thank you ~作者tag:正则表达式cookie xml操作禁止复制屏蔽焦点按钮节点透明画图判断全屏下拉框弹出窗口下载文件js收集自动关闭模式窗口字符转化为数字页内跳转网页自动跑同时按下删除表格某行判断浏览器生成excel 菜单中的命令的实现给下拉框分组窗口重定向能输入的下拉框js技巧收集(200多个)1.文本框焦点问题onBlur:当失去输入焦点后产生该事件onFocus:当输入获得焦点后,产生该文件Onchange:当文字值改变时,产生该事件Onselect:当文字加亮后,产生该文件<input type="text" value="郭强" onfocus="if(value=='郭强') {value=''}" onblur="if(value=='') {value='郭强'}">点击时文字消失,失去焦点时文字再出现2.网页按钮的特殊颜色<input type=button name="Submit1" value="郭强" size=10 class=s02style="background-color:rgb(235,207,22)">3.鼠标移入移出时颜色变化<input type="submit" value="找吧" name="B1" onMouseOut=this.style.color="blue"onMouseOver=this.style.color="red" class="button">4.平面按钮<input type=submit value=订阅style="border:1px solid :#666666; height:17px; width:25pt; font-size:9pt;BACKGROUND-COLOR: #E8E8FF; color:#666666" name="submit">5.按钮颜色变化<input type=text name="nick" style="border:1px solid #666666; font-size:9pt; height:17px;BACKGROUND-COLOR: #F4F4FF; color:#ff6600" size="15" maxlength="16">6.平面输入框<input type="text" name="T1" size="20" style="border-style: solid; border-width: 1">7.使窗口变成指定的大小<script>window.resizeTo(300,283);</script>8.使文字上下滚动<marquee direction=up scrollamount=1 scrolldelay=100 onmouseover='this.stop()' onmouseout='this.start()'height=60><!-- head_scrolltext --><tr><td>共和国</table> <!-- end head_scrolltext --></marquee>9.状态栏显示该页状态<base onmouseover="window.status='网站建设/' ;return true">10.可以点击文字实现radio选项的选定<br>&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="regtype" value="A03" id="A03"><label for="A03"> 情侣: 一次注册两个帐户</label> <br>11.可以在文字域的font写onclick事件12.打印</a>打印网页<a href='javascript:window.print ()'>13.线型输入框<input type="text" name="key" size="12" value="关键字" onFocus=this.select() onMouseOver=this.focus()class="line">14.显示文档最后修改日期<script language=javascript>function hi(str){document.write(stModified)alert("hi"+str+"!")}</script>15.可以在鼠标移到文字上时就触发事件<html><head><script language="LiveScript"><!-- Hidingfunction hello() {alert("哈罗!");}</script></head><body><a href="" onMouseOver="hello()">link</a></body></html>16.可以根据网页上的选项来确定页面颜色<HTML><HEAD><TITLE>background.html</TITLE></HEAD><SCRIPT><!--function bgChange(selObj) {newColor = selObj.options[selObj.selectedIndex].text; document.bgColor = newColor;selObj.selectedIndex = -1;}//--></SCRIPT><BODY STYLE="font-family:Arial"><B>Changing Background Colors</B><BR><FORM><SELECT SIZE="8" onChange="bgChange(this);"> <OPTION>Red<OPTION>Orange<OPTION>Yellow<OPTION>Green<OPTION>Blue<OPTION>Indigo<OPTION>Violet<OPTION>White<OPTION>pink</SELECT></FORM></BODY></HTML>17.将按钮的特征改变<style type="text/css"><!--.style1 { font-size: 12px; background: #CCCCFF; border-width: thin thin thin thin; border-color: #CCCCFF#CCCCCC #CCCCCC #CCCCFF}.style2 { font-size: 12px; font-weight: bold; background: #CCFFCC; border-width: thin medium medium thin;border-color: #CCFF99 #999999 #999999 #CCFF99}--></style>本例按钮的代码如下:<input type="submit" name="Submit" value="提交" onmouseover="this.className='style2'"onmouseout="this.className='style1'" class="style1">18.改变按钮的图片.<style type="text/css"><!--.style3 { font-size: 12px; background: url(image/buttonbg1.gif); border: 0px; width: 60px; height: 22px}.style4 { font-size: 12px; font-weight: bold; background: url(image/buttonbg2.gif); border: 0px 0; width:60px; height: 22px}--></style>本例的按钮代码如下:<input type="submit" name="Submit2" value="提交" onmouseover="this.className='style4'"onmouseout="this.className='style3'" class="style3">19.打印页面<div align="center"><a class=content href="javascript:doPrint();">打印本稿</a></div>20.可以直接写html语言document.write("");21.改变下拉框的颜色<select name="classid"onChange="changelocation(document.myform.classid.options[document.myform.classid.selectedI ndex].value)"size="1" style="color:#008080;font-size: 9pt">22.转至目标URLwindow.location="http://guoguo"23.传递该object的formUpdateSN('guoqiang99267',this.form)function UpdateSN(strValue,strForm){strForm.SignInName.value = strValue;return false;}24.文字标签<label for="AltName4"><input name="AltName" type="RADIO" tabindex="931" id="AltName4">guoqiang99859</label>yer2为组件的ID,可以控制组件是否可见document.all.item('Layer2').style.display = "block";document.all.item('Layer2').style.display = "none";//26.将页面加入favorite中<script language=javascript><!--function Addme(){url = "http://your.site.address"; //你自己的主页地址title = "Your Site Name"; //你自己的主页名称window.external.AddFavorite(url,title);--></script>//27.过10秒自动关闭页面< script language="JavaScript" >function closeit() {setTimeout("self.close()",10000)}< /script >28.可以比较字符的大小char=post.charAt(i);if(!('0'<=char&&char<='9'))29.将字符转化为数字month = parseInt(char)30.点击value非空的选项时转向指定连接<select onchange='if(this.value!="")window.open(this.value)' class="textinput"> <option selected>主办单位</option><option>-----------------</option><option value="/">北京日报</option><option value="/">北京晚报</option></select>31.改变背景颜色<td width=* class=dp bgColor=#FAFBFC onmouseover="this.bgColor='#FFFFFF';" onmouseout="this.bgColor='#FAFBFC';">32.改变文字输入框的背景颜色<style>.input2 {background-image: url('../images/inputbg.gif'); font-size: 12px; background-color:#D0DABB;border-top-width:1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px}</style><input name=content type=text size="47" class="input2" maxlength="50">33.改变水平线的特征<hr size="0" noshade color="#C0C0C0">34.传递参数的方式<a href="vote.asp?CurPage=8&id=3488">8</a>35.页内跳转<a href="#1">1</a><a href="#2">2</a><a href="#3">3</a><a href="#4">4</a><a href="#5">5</a><a href="#6">6</a><a href="#7">7</a>。

给JavaScript初学者的24个小窍门

给JavaScript初学者的24个小窍门

为JavaScript做一点性能小提升吧!本文列出了24条能让你的代码编写过程更为轻松高效的建议。

也许您还是JavaScript 初学者,刚刚写完自己的Hello World,那这里有很多对您的工作将十分有用的小贴士;也许有些技巧您已经知道,那就试试快速浏览一下,看能不能发现一点新东西吧!1. 用 === 代替 ==JavaScript里有两种不同的相等运算符:===|!== 和==|!=。

相比之下,前者更值得推荐。

请尽量使用前者。

“如果两个比较对象有着同样的类型和值,===返回true,!==返回false。

”– JavaScript: The Good Parts不过,如果使用==和!=,在操作不同数据类型时, 你可能会遇到一些意想不到的问题。

在进行相等判断前,JavaScript会试图将它们转换为字符串、数字或 Boolean量。

2. 避免使用Eval函数Eval函数把一个字串作为参数,并把字串作为JavaScript语句执行,返回结果。

此函数不仅会降低你脚本的执行效率,而且还大大增加了安全风险,因为它赋予了作为文本的参数太大的权利。

千万别用!3. 不要使用快速写法技术上说,你可以省略掉大部分花括弧和句尾分号,绝大多数浏览器都能正确执行以下语句:1.if(someVariableExists)2.x = false不过,如果是这样的呢:3.if(someVariableExists)4.x = false5.anotherFunctionCall();你可能会认为它和下面的语句相等:6.if(someVariableExists) {7.x = false;8.anotherFunctionCall();9.}不幸的是,事实并非如此。

现实情况是它等价于:10.if(someVariableExists) {11.x = false;12.}13.anotherFunctionCall();如您注意到的,再漂亮的缩进也不能代替这华丽的花括弧。

前端基础之JavaScript

前端基础之JavaScript

前端基础之JavaScript知识预览:JavaScript概述JavaScript的历史1992年Nombas开发出C-minus-minus (C--) 的嵌⼊式脚本语⾔(最初绑定在CEnvi软件中).后将其改名ScriptEase.(客户端执⾏的语⾔)Netscape(⽹景)接收Nombas的理念,(Brendan Eich)在其Netscape Navigator 2.0产品中开发出⼀套livescript的脚本语⾔.Sun和Netscape共同完成.后改名叫Javascript 微软随后模仿在其IE3.0的产品中搭载了⼀个JavaScript的克隆版叫Jscript.为了统⼀三家,ECMA(欧洲计算机制造协会)定义了ECMA-262规范.国际标准化组织及国际电⼯委员会(ISO/IEC)也采纳 ECMAScript 作为标准(ISO/IEC-16262)。

从此,Web 浏览器就开始努⼒(虽然有着不同的程度的成功和失败)将 ECMAScript 作为 JavaScript 实现的基础。

EcmaScript是规范.ECMAScript尽管 ECMAScript 是⼀个重要的标准,但它并不是 JavaScript 唯⼀的部分,当然,也不是唯⼀被标准化的部分。

实际上,⼀个完整的 JavaScript 实现是由以下 3 个不同部分组成的:核⼼(ECMAScript)⽂档对象模型(DOM) Document object model (整合js,css,html)浏览器对象模型(BOM) Broswer object model(整合js和浏览器)Javascript 在开发中绝⼤多数情况是基于对象的.也是⾯向对象的.简单地说,ECMAScript 描述了以下内容:语法类型语句关键字保留字运算符对象 (封装继承多态) 基于对象的语⾔.使⽤对象.JavaScript的基础2.1 JS的引⼊⽅式1 直接编写<script>alert('hello yuan')</script>2 导⼊⽂件<script src="hello.js"></script>2.2 JS的变量、常量和标识符2.2.1 JS的变量x=5y=6z=x+y在代数中,我们使⽤字母(⽐如 x)来保存值(⽐如 5)。

jsjavascript计时器方法及使用场景

jsjavascript计时器方法及使用场景

jsjavascript计时器⽅法及使⽤场景开博以备忘JavaScript实现计时事件很容易,两个关键⽅法setTimeout(“JavaScript语句”,毫秒) 未来的某时执⾏代码clearTimeout() 取消setTimeout()setTimeout⽅法会返回⼀个整数,表⽰计时器的标号,var t = setTimeout(“javascript语句”,毫秒) ,值会存储在变量t中,需要取消这个计时的话可以利⽤变量来指定它,clearTimeout(t)以下是计时器相关⽅法及使⽤场景,注意事项setTimeout()setTimeout函数⽤来指定某个函数或某段代码,在多少毫秒之后执⾏。

它返回⼀个整数,表⽰定时器的编号,以后可以⽤来取消这个定时器。

var timerId = setTimeout(func|code, delay);上⾯代码中,setTimeout函数接受两个参数,第⼀个参数func|code是将要推迟执⾏的函数名或者⼀段代码,第⼆个参数delay是推迟执⾏的毫秒数。

console.log(1);setTimeout('console.log(2)',1000);console.log(3);// 1// 3// 2上⾯代码会先输出1和3,然后等待1000毫秒再输出2。

注意,console.log(2)必须以字符串的形式,作为setTimeout的参数。

如果推迟执⾏的是函数,就直接将函数名,作为setTimeout的参数。

function f() {console.log(2);}setTimeout(f, 1000);setTimeout的第⼆个参数如果省略,则默认为0。

setTimeout(f)// 等同于setTimeout(f, 0)除了前两个参数,setTimeout还允许更多的参数。

它们将依次传⼊推迟执⾏的函数(回调函数)。

setTimeout(function (a,b) {console.log(a + b);}, 1000, 1, 1);上⾯代码中,setTimeout共有4个参数。

Javascript教程--从入门到精通【完整版】

Javascript教程--从入门到精通【完整版】

Javascript教程--从入门到精通【完整版】(作者:未知,来源:互联网整理:Alone)JavaScript教程语言概况Internet时代,造就了我们新的工作和生活方式,其互联性、开放性和共享信息的模式,打破了传统信息传播方式的重重壁垒,为我们带来了新的机遇。

随着计算机和信息时代的到来,人类社会前进的脚步在逐渐加快,每一天都有新的事情发生,每一天都在创造着奇迹。

随着Internet技术的突飞猛进,各行各业都在加入Internet的行业中来。

无论从管理方面,还是从商业角度来看,Internet都可以带来无限生机。

通过Internet,可以实现地区、集体乃至个人的连接,从而达到一种“统一的和谐”。

那么怎样把自己的或公司的信息资源加入到WWW 服务器,是广大用户日益关心的问题。

采用超链技术(超文本和超媒体技术)是实现这个目标最简单的、最快速的手段和途径。

具体实现这种手段的支持环境,那就是HTML超文本标识语言。

通过它们可制作所需的Web网页。

通过超文本(Hyper Text)和超媒体(Hyper Media)技术结合超链接(Hyper link)的链接功能将各种信息组织成网络结构(web),构成网络文档(Document),实现Internet上的“漫游”。

通过HTML符号的描述就可以实现文字、表格、声音、图像、动画等多媒体信息的检索。

然而采用这种超链技术存在有一定的缺陷,那就是它只能提供一种静态的信息资源,缺少动态的客户端与服务器端的交互。

虽然可通过CGI(Common Gateway Interface)通用网关接口实现一定的交互,但由于该方法编程较为复杂,因而在一段时间防碍了Internet技术的发展。

而JavaScript的出现,无凝为Internet网上用户带来了一线生机。

可以这样说,JavaScript的出现是时代的需求,是当今的信息时代造就了JavaScript。

JavaScript的出现,它可以使得信息和用户之间不仅只是一种显示和浏览的关系,而是实现了一种实时的、动态的、可交式的表达能力。

JavaScript学习资料演示课件

JavaScript学习资料演示课件
事件绑定方式
通过HTML标签属性直接绑定事件处理函数,或在JavaScript代码中使用`addEventListener()`方法绑定事件处理 函数。后者支持同时绑定多个事件处理函数,且事件处理函数中的`this`指向当前元素。
事件流模型及阻止默认行为
事件流模型
包括捕获阶段、目标阶段和冒泡阶段。在捕获阶段,事件从 顶层元素向下传递,直到触发目标元素的事件处理函数;在 冒泡阶段,事件从目标元素向上冒泡,直到顶层元素。
使用CDN加速
将JavaScript文件部署在CDN上,利用CDN的分布式网络加速文件传 输,提高加载速度。
异步加载和延迟执行
通过async和defer属性实现JavaScript的异步加载和延迟执行,避免 阻塞页面渲染。
利用浏览器缓存
通过设置HTTP缓存头信息,使浏览器缓存JavaScript文件,减少重复 请求和加载时间。
利用WeakMap和WeakSet处理弱…
使用WeakMap和WeakSet可以自动处理对象之间的弱引用关系,避 免内存泄漏。
渲染性能优化策略
减少重排和重绘
通过避免不必要的DOM操作、使用transform代替top/left等优化手 段,减少页面的重排和重绘次数。
使用requestAnimationFr…
03
AJAX 基于 JavaScript、XML、HTML、CSS 和 DOM 等多种技术组合而成。
XMLHttpRequest对象使用
XMLHttpRequest 是 AJAX 的 基础,用于在后台与服务器交换
数据。
通过创建 XMLHttpRequest 对 象,可以打开一个连接、发送请
求并处理响应。
了解jQuery中的事件绑定、事件冒泡、事 件委托等概念,实现交互效果。

怎么轻松快速学习JavaScript

怎么轻松快速学习JavaScript

怎么轻松快速学习JavaScript?JS给初学者的形象总是那么的“杂而乱”,信任许多初学者都在找轻松学习js的途径。

我试着总结自己学习多年js的经历,期望能给后来的学习者探究出一条“轻松学习js之路”。

其实js入门并不难,难的是精通。

就像之前的小学数学一样,随便一个正常人都能考试90分以上,但到了初中以上,数学的难度就呈几何倍数的增加。

JS给人那种感觉的原因多半是因为它如下的特点:1:本身知识很抽象、晦涩难懂,如:闭包、内置对象、DOM。

2:本身内容很多,如函数库,对象库就一大堆。

3:混合多种编程思想。

4:辛苦学习后又看似和实际应用脱节。

通常学了很久的JS基础之后,变量、函数、对象你也都略知一二,但一到公司开发项目的时候,却又难以下手。

因为公司在开发实际项目的时候通常都是直接用它的衍生库,比如:jquery,angular,boostrap,等,而这些库又多如牛毛,同时还有自己的难点。

让你都不知道该学哪个好,甚至开始怀疑人生,有木有!如何轻松快速学习JavaScriptA:js基础部分,如:定义变量、函数、数组、字符串等的处理,内置函数、内置对象等。

(添加小编扣扣:1036528502,可以领取全套js基础视频教程哦)B:js面向过程编程思想,封装出各个函数,试着用这些去做一些常见的小功能,如:选项卡,自定义多选按钮,自定义播放器,3D幻灯片;如何轻松快速学习JavaScriptC:js面向对象编程思想,试着去封装一些你自己的对象,提供出有意义的接口出来;D:学了上述的内容,然后学常用的库,这里必须学jquery; E:学基于Jquery之上的常见插件,如:bootstrap,Layer,富文本编辑器等。

F:综合应用上面的多种库写实际项目的模板,多写几套。

JavaScript小技巧介绍

JavaScript小技巧介绍

JavaScript小技巧介绍能够为大家提供这些简短而实用的JavaScript技巧来提高大家编程能力,这对于我来说是件很开心的事。

每天仅花上不到2分钟的时间中,你将可以读遍JavaScript这门可怕的语言所呈现给我们的特性:performance(性能), conventions(协议), hacks(代码hack), interview questions(面试问题)及所有其他的项。

#24 - 使用=== 代替====(或者!=)做对比的时候会将进行对比的两者转换到同一类型再比较。

===(或者!==)则不会,他会将进行对比的两者做类型对比和值对比,相对于== ,=== 的对比会更加严谨。

[10] == 10 // true[10] === 10 // false"10" == 10 // true"10" === 10 // false[] == 0 // true[] === 0 // false"" == false// true 但是true == "a" 是false"" === false// false#23 - 转换数值的更加的方法将字符串转换为数字是非常常见的。

最简单和最快的(jspref)的方式来实现,将使用+(加)算法。

var one = '1';varnumberOne = +one; // Number 1你也可以使用-(减号)算法的转换类型并且变成负数值。

var one = '1';varnegativeNumberOne = -one; // Number -1#22 - 清空一个数组你定义一个数组,并希望清空它的内容。

通常,你会这样做:var list = [1, 2, 3, 4];function empty() {//清空数组list = [];}empty();但是还有一种更高性能的方法。

js倒计时代码最简单的

js倒计时代码最简单的

js倒计时代码最简单的最简单的倒计时代码是使用JavaScript实现的。

JavaScript是一种脚本语言,可以在网页上实现各种功能。

倒计时是其中一种常见的功能需求,可以用于展示活动倒计时、秒杀倒计时等场景。

要实现倒计时功能,首先需要定义一个截止时间,然后通过不断更新当前时间与截止时间的时间差来显示倒计时。

以下是一个使用JavaScript实现的最简单的倒计时代码:```javascript// 定义截止时间var deadline = new Date('2022-01-01 00:00:00');// 更新倒计时function updateCountdown() {// 获取当前时间var now = new Date();// 计算时间差var diff = deadline - now;// 计算剩余的天、小时、分钟和秒var days = Math.floor(diff / (1000 * 60 * 60 * 24));var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 *60));var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));var seconds = Math.floor((diff % (1000 * 60)) / 1000);// 显示倒计时console.log('距离截止时间还有:' + days + '天 ' + hours + '小时 ' + minutes + '分钟 ' + seconds + '秒');// 如果倒计时结束,清除定时器if (diff <= 0) {clearInterval(timer);console.log('倒计时结束');}}// 每秒更新一次倒计时var timer = setInterval(updateCountdown, 1000);```在上述代码中,首先定义了一个截止时间`deadline`,然后通过`setInterval` 函数每秒调用一次 `updateCountdown` 函数来更新倒计时。

JavaScript实现简单计时器

JavaScript实现简单计时器

JavaScript实现简单计时器本⽂实例为⼤家分享了JavaScript实现简单计时器的具体代码,供⼤家参考,具体内容如下<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>计时器</title><style>.bigDiv {margin: 50px auto;width: 200px;height: 200px;background-color: lightskyblue;border-radius: 10px;}#showNum {width: 200px;height: 20px;background-color: orange;text-align-all: center;border-radius: 5px;}</style></head><body><div class="bigDiv"><h2 align="center">计时器</h2><div id="showNum" align="center"></div><br><br><div class="butDiv">&nbsp&nbsp&nbsp&nbsp<button type="button" id="start">开始</button>&nbsp<button type="button" id="stop">停⽌</button>&nbsp<button type="button" id="reset">复位</button>&nbsp</div></div><script>//定义显⽰的时间let int = null;/*** 开始单击事件*/document.getElementById("start").addEventListener('click', function () {if (int == null) {//设置定时器//每隔参数⼆毫秒执⾏⼀次参数⼀int = setInterval(startNum, 1000);}});/*** 停⽌单击事件*/document.getElementById("stop").addEventListener('click', function () {//清除定时器,clearInterval(int);int = null;});/*** 复位单击事件*/let num = 0;document.getElementById("reset").addEventListener('click', function () {if (int == null) {num = 0;//将时间变成0document.getElementById("showNum").innerHTML = num;}});function startNum() {num++;//持续改变时间document.getElementById("showNum").innerHTML = num;}</script></body></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

javascript实现计时器的简单方法

javascript实现计时器的简单方法

javascript实现计时器的简单⽅法计时器, 在⽣活当中也是⽤得频繁的功能, ⽐如锻炼⾝体, 跑步⽐赛等等相关的活动. 我们⽤Javascript来完成⼀个计时器.计时器, 主要就是对时间的⼀个逻辑处理, ⽐如60秒等于1分钟, 60分钟等于⼀个⼩时, 我们这⾥只做到⼩时的处理. 就这么⼀个简单的逻辑, 然后动态的显⽰在⼀个Input⾥⾯.那现在我们来完成这个界⾯<label>计时:</label><input type="text" name="" id="timer"/><button onclick="pause(this)" id="pause" state="on">暂停</button><button onclick="restart()">重新开始</button>给标签元素⼀个ID是为了获取其中的标签, 然后加⼊了两个点击事件, 计数器的暂停, 和重新开始事件.⾸先我们来完成开始计时的处理, 开始计时主要还是是⽤了setInterval的⽅法, 其中每隔1秒执⾏⼀次⽅法, 这样我们就可以对时间做处理, 就像开头所说60秒等于1分钟..., 所以这⾥就需要⽤判断来处理, 最后就将其中的得到的秒,分,时显⽰到输⼊框⾥.var ele_timer = document.getElementById("timer");var n_sec = 0; //秒var n_min = 0; //分var n_hour = 0; //时//60秒 === 1分//60分 === 1⼩时function timer() {return setInterval(function () {var str_sec = n_sec;var str_min = n_min;var str_hour = n_hour;if ( n_sec < 10) {str_sec = "0" + n_sec;}if ( n_min < 10 ) {str_min = "0" + n_min;}if ( n_hour < 10 ) {str_hour = "0" + n_hour;}var time = str_hour + ":" + str_min + ":" + str_sec;ele_timer.value = time;n_sec++;if (n_sec > 59){n_sec = 0;n_min++;}if (n_min > 59) {n_sec = 0;n_hour++;}}, 1000);}var n_timer = timer();我们⽤timer⽅法包装setInterval⽅法是为了,后⾯暂停和重新开始做处理.⽤户点击了暂停, 计时器就停⽌计时, ⽤户继续点击这个按钮, 计时器继续计时. 所以这⾥有⼀个状态需要控制,这个状态我们给这个按钮⼀个属性.//暂停和继续function pause(self) {var state = self.getAttribute("state");if (state === "on") {clearInterval(n_timer);self.textContent = "继续";self.setAttribute("state", "off");} else {n_timer = timer();self.textContent = "暂停";self.setAttribute("state", "on");}}最后我们来看⼀下重新开始, 重新开始事件就更加简单了. 将计数器清0, 然后改变暂停按钮初始状态. function restart() {clearInterval(n_timer);n_sec = 0;n_min = 0;n_hour = 0;n_timer = timer();var ele_pause = document.getElementById("pause");ele_pause.textContent = "暂停";ele_pause.setAttribute("state", "on");}这样就完成了计时的功能.效果如下希望本⽂所述对⼤家学习javascript程序设计有所帮助。

javascript实现动态时钟的启动和停止

javascript实现动态时钟的启动和停止

javascript实现动态时钟的启动和停⽌javascript实现动态时钟的启动和停⽌,点击开始按钮,获取当前时间,点击停⽌按钮,时间停⽌<!DOCTYPE html><html><head><meta charset="UTF-8"><title>动态时钟的启动和停⽌</title></head><body background="img/2.jpg" style="background-repeat: no-repeat;margin-left: 180px;"><!--1.显⽰当前时间2.启动秒表3.停⽌时钟--><h1>动态时钟</h1><p>当前时间:<span id="clock" style="color: #FF0000;"/> </span></p><p><input type="button" value="start" onclick="start()" style="color: #FF0000;"/><input type="button" value="stop" onclick="stop()" style="color: #FF0000;"/></p></body><script type="text/javascript">var timer;function start(){//设置定时器(⽅法的实现,毫秒数)timer=setInterval(function(){var now=new Date();var time=now.toLocaleTimeString();var c=document.getElementById("clock");c.innerHTML=time;},1000);}function stop(){//暂停清楚定时器clearInterval(timer);}</script></html>效果截图:更多JavaScript时钟特效点击查看:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

javascript时刻全解析

javascript时刻全解析

javascript时刻全解析(Date,setInterval,document)(一句废话下载0财富,要用先下载)废话少说,先上成效图:代码跟上:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>js日期格式化函数农历日期时刻十分秒走动</title><meta name="description" content="js日期格式化函数设置多种时刻日期格式显示,农历日期时刻,十分秒走动时刻。

7种农历日期时刻显示。

js代码" /></head><body><style type="text/css">*{margin:0;padding:0;list-style-type:none;}a,img{border:0;}.time{height:32px;line-height:32px;overflow:hidden;font-size:14px;width:300px;margin:20px auto;border:solid 1px #ddd;padding:0 10px;background:#F7F7F7;}</style><script type="text/javascript">function initArray(){for(i=0;i<initArray.arguments.length;i++)this[i]=initArray.arguments[i];}var isnMonths=new initArray("1","2","3","4","5","6","7","8","9","10","11","12 ");var isnDays=new initArray("礼拜日","礼拜一","礼拜二","礼拜三","礼拜四","礼拜五","礼拜六","礼拜日");today=new Date();hrs=today.getHours();min=today.getMinutes();sec=today.getSeconds();clckh=""+((hrs>12)?hrs-12:hrs);clckm=((min<10)?"0":"")+min;clcks=((sec<10)?"0":"")+sec;clck=(hrs>=12)?"下午":"上午";var stnr="";var ns="0123456789";var a="";function getFullYear(d){yr=d.getYear();if(yr<1000)yr+=1900;return yr;}</script><script type="text/javascript">//下面各行别离是一种风格,把不需要的删掉即可document.write("<div class='time'>"+ getFullYear(today)+"年" + ","+ isnMonths[today.getMonth()] +"月"+ today.getDate() +"日,"+ isnDays[today.getDay()] +"</div>");document.write("<div class='time'>"+getFullYear(today)+"年"+","+isnMonths[today.getMonth()]+"月"+today.getDate()+"日,"+isnDays[today.getDay()]+","+clck+""+clckh+":"+clckm+": "+clcks+"</div>");document.write("<divclass='time'>"+(getFullYear(today)+"").substring(0,4)+"/"+( today.getMonth()+1)+"/"+today.getDate()+"</div>");document.write("<divclass='time'>"+hrs+":"+clckm+":"+clcks+"</div>");document.write("<div class='time'>"+today+"</div>");</script><!--农历日期--><script type="text/javascript">//============================日期var sWeek = new Array("礼拜日", "礼拜一", "礼拜二", "礼拜三", "礼拜四", "礼拜五", "礼拜六");var dNow = new Date();var CalendarData = new Array(100);var madd = new Array(12);var tgString = "甲乙丙丁戊己庚辛壬癸";var dzString = "子丑寅卯辰巳午未申酉戌亥";var numString = "一二三四五六七八九十";var monString = "正二三四五六七八九十冬腊";var weekString = "日一二三四五六";var sx = "鼠牛虎兔龙蛇马羊猴鸡狗猪";var cYear, cMonth, cDay, TheDate;CalendarData = new Array(0xA4B, 0x5164B, 0x6A5, 0x6D4, 0x415B5, 0x2B6, 0x957, 0x2092F, 0x497, 0x60C96,0xD4A, 0xEA5, 0x50DA9, 0x5AD, 0x2B6, 0x3126E, 0x92E, 0x7192D, 0xC95, 0xD4A,0x61B4A, 0xB55, 0x56A, 0x4155B, 0x25D, 0x92D, 0x2192B,0xA95, 0x71695, 0x6CA,0xB55, 0x50AB5, 0x4DA, 0xA5B, 0x30A57, 0x52B, 0x8152A, 0xE95, 0x6AA, 0x615AA,0xAB5, 0x4B6, 0x414AE, 0xA57, 0x526, 0x31D26, 0xD95, 0x70B55, 0x56A, 0x96D,0x5095D, 0x4AD, 0xA4D, 0x41A4D, 0xD25, 0x81AA5, 0xB54, 0xB6A, 0x612DA, 0x95B,0x49B, 0x41497, 0xA4B, 0xA164B, 0x6A5, 0x6D4, 0x615B4, 0xAB6, 0x957, 0x5092F,0x497, 0x64B, 0x30D4A, 0xEA5, 0x80D65, 0x5AC, 0xAB6, 0x5126D, 0x92E, 0xC96,0x41A95, 0xD4A, 0xDA5, 0x20B55, 0x56A, 0x7155B, 0x25D, 0x92D, 0x5192B, 0xA95,0xB4A, 0x416AA, 0xAD5, 0x90AB5, 0x4BA, 0xA5B, 0x60A57, 0x52B, 0xA93, 0x40E95);madd[0] = 0; madd[1] = 31; madd[2] = 59; madd[3] = 90;madd[4] = 120; madd[5] = 151; madd[6] = 181; madd[7] = 212;madd[8] = 243; madd[9] = 273; madd[10] = 304; madd[11] = 334;function GetBit(m, n) { return (m >> n) & 1; }function e2c() {TheDate = (arguments.length != 3) ? new Date() : new Date(arguments[0], arguments[1], arguments[2]);var total, m, n, k;var isEnd = false;var tmp = TheDate.getFullYear();total = (tmp - 1921) * 365 + Math.floor((tmp - 1921) / 4) + madd[TheDate.getMonth()] + TheDate.getDate() - 38; if (TheDate.getYear() % 4 == 0 && TheDate.getMonth() > 1) { total++; } for (m = 0; ; m++) { k = (CalendarData[m] < 0xfff) ?11 : 12; for (n = k; n >= 0; n--) { if (total <= 29 + GetBit(CalendarData[m], n)) { isEnd = true; break; } total = total - 29 - GetBit(CalendarData[m], n); } if (isEnd) break; } cYear = 1921 + m; cMonth = k - n + 1; cDay = total; if (k == 12) { if (cMonth == Math.floor(CalendarData[m] / 0x10000) + 1) { cMonth = 1 - cMonth; } if (cMonth > Math.floor(CalendarData[m] / 0x10000) + 1) { cMonth--; } }}function GetcDateString() {var tmp = ""; tmp += tgString.charAt((cYear - 4) % 10);tmp += dzString.charAt((cYear - 4) % 12);tmp += "年 ";if (cMonth < 1) { tmp += "(闰)"; tmp += monString.charAt(-cMonth - 1); } else { tmp += monString.charAt(cMonth - 1); } tmp += "月"; tmp += (cDay < 11) ?"初" : ((cDay < 20) ? "十" : ((cDay < 30) ? "廿" : "三十"));if (cDay % 10 != 0 || cDay == 10) { tmp += numString.charAt((cDay - 1) % 10); } return tmp;}function GetLunarDay(solarYear, solarMonth, solarDay) { if (solarYear < 1921 || solarYear > 2020) {return "";} else { solarMonth = (parseInt(solarMonth) > 0) ? (solarMonth - 1) : 11; e2c(solarYear, solarMonth, solarDay); return GetcDateString(); }}var D = new Date();var yy = D.getFullYear();var mm = D.getMonth() + 1;var dd = D.getDate();var ww = D.getDay();var ss = parseInt(D.getTime() / 1000);function getFullYear(d) {// 修正firefox下year错误yr = d.getYear(); if (yr < 1000)yr += 1900; return yr;}function showDate() {timeString = new Date().toLocaleTimeString();var sValue = getFullYear(dNow) + "年" + (dNow.getMonth() + 1) + "月" + dNow.getDate() + "日 " + sWeek[dNow.getDay()] + " "; // + " " + timeString + " "sValue += GetLunarDay(yy, mm, dd);var svalue1 = getFullYear(dNow) + "年" + (dNow.getMonth() + 1) + "月" + dNow.getDate() + "日";var svalue2 = timeString;var svalue3 = GetLunarDay(yy, mm, dd);var sx2 = sx.substr(dzString.indexOf(svalue3.substr(1, 1)), 1);var svalue33 = svalue3.substr(0, 3)var svalue333 = svalue33.substr(0, 2) + "(" + sx2 + ")" + svalue33.substr(2, 1);var sx22 = "农历" + svalue3.substr(4, 6);document.write(sValue);}</script><div class="time"><script language="javascript">showDate()</script></div><!--十,分,秒--><script type="text/javascript"> function showLocale(obj){var str;var hh = obj.getHours();if(hh<10)hh = '0' + hh;var mm = obj.getMinutes();if(mm<10) mm = '0' + mm;var ss = obj.getSeconds();if(ss<10) ss = '0' + ss;str = hh + ":" + mm + ":" + ss;return(str);}function tick(){var today;today = new Date();document.getElementById("clock").innerHTML = showLocale(today);window.setTimeout("tick()", 1000);}</script><div class="time" id="clock"></div><script type="text/javascript">tick()</script></body></html>代码完了,扩展点知识:var myDate = new Date();myDate.getYear(); //获取当前年份(2位)myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate.getDate(); //获取当前日(1-31)myDate.getDay(); //获取当前星期X(0-6,0代表星期天) myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)myDate.getHours(); //获取当前小时数(0-23)myDate.getMinutes(); //获取当前分钟数(0-59)myDate.getSeconds(); //获取当前秒数(0-59)myDate.getMilliseconds(); //获取当前毫秒数(0-999) myDate.toLocaleDateString(); //获取当前日期var mytime=myDate.toLocaleTimeString(); //获取当前时间myDate.toLocaleString( ); //获取日期与时间脚本库方式列表.prototype.isLeapYear 判定闰年Date.prototype.Format 日期格式化Date.prototype.DateAdd 日期计算Date.prototype.DateDiff 比较日期差Date.prototype.toString 日期转字符串Date.prototype.toArray 日期分割为数组Date.prototype.DatePart 取日期的部分信息Date.prototype.MaxDayOfDate 取日期所在月的最大Date.prototype.WeekNumOfYear 判断日期所在年的第几周StringToDate 字符串转日期型IsValidDate 验证日期有效性CheckDateTime 完整日期时间检查daysBetween 日期天数差在载人页面后,阅读器输出流自动关闭;在此以后,任何一个对当前页面进行操作的document.write()方式将打开—个新的输出流。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Javascript in Ten MinutesSpencer TippingDecember22,2010Contents1Introduction3 2Types3 3Functions43.1Variadic behavior(a cool thing) (4)3.2Lazy scoping(a cool thing) (4)3.3The meaning of this(the egregious disaster) (5)3.3.1Important consequence:eta-reduction (6)4Gotchas74.1Semicolon inference (7)4.2Void functions (7)4.3var (8)4.4Lazy scoping and mutability (8)4.5Equality (9)4.6Boxed vs.unboxed (9)4.7Things that will silently fail or misbehave (10)4.8Things that will loudly fail (11)4.9Throwing things (11)4.10Be careful with typeof (11)4.11Also be careful with instanceof (12)4.12Browser incompatibilities (13)5Prototypes135.1Why new is awful (14)5.2Why you should use prototypes (15)5.3Autoboxing (15)6A Really Awesome Equality1517If You Have20Minutes (16)7.1Forwarding constructors (17)7.2Iterators for cool people (17)7.3Java classes and interfaces (18)7.4Recursive metaclasses (19)7.5Tail calls and delimited continuations (20)7.6Syntactic macros and operator overloading (22)8Further reading2421IntroductionThis guide is for anyone who knows some Javascript but would like a quick1intro to its advanced features.It will be easier reading if you also know another functional language such as Ruby,Perl,Python,ML,Scheme,etc,since I don’treally explain howfirst-class functions work.2TypesJavascript has nine types.They are:1.Null–null.Chucks a wobbly if you ask it for any attributes;e.g.null.foofails.Never boxed.22.Undefined–undefined.What you get if you ask an object for somethingit doesn’t have;e.g.document.nonexistent.Also chucks a wobbly if youask it for any attributes.Never boxed.3.Strings–e.g.’foo’,"foo"(single vs.double quotation marks makes nodifference).Sometimes boxed.Instance of String when boxed.4.Numbers–e.g.5,3e+10(all numbers behave asfloats–significant fordivision,but can be truncated by x>>>0).Sometimes boxed.Instanceof Number when boxed.5.Booleans–true and false.Sometimes boxed.Instance of Boolean whenboxed.6.Arrays–e.g.[1,2,"foo",[3,4]].Always boxed.Instance of Array.7.Objects–e.g.{foo:’bar’,bif:[1,2]},which are really just hashta-bles.Always boxed.Instance of Object.8.Regular expressions–e.g./foo\s*([bar]+)/.Always boxed.Instanceof RegExp.9.Functions–e.g.function(x){return x+1}.Always boxed.In-stance of Function.The value null is actually almost never produced by Javascript.The onlycase you’re likely to run across null is if you assign it somewhere(most of thetime you’ll get undefined instead–one notable exception is document.getElementById, which returns null if it can’tfind an element).Making sparing use of undefinedand instead using null can make bugs much easier to track down.1Longer than ten minutes,despite what the title says.2Boxing is just a way of saying whether something has a pointer.A boxed type is a referencetype,and an unboxed type is a value type.In Javascript,this has additional ramifications as well–see section4.6.33FunctionsFunctions arefirst-class lexical closures,3just like lambda s in Ruby or sub s inPerl.4They behave pretty much like you’d expect,but there are several reallycool things about functions and one really egregious disaster.3.1Variadic behavior(a cool thing)Functions are always variadic.5Formal parameters are bound if they’re present;otherwise they’re undefined.For example:(function(x,y){return x+y})(’foo’)//=>’fooundefined’The arguments to your function can be accessed in afirst-class way,too:var f=function(){return arguments[0]+arguments[1]};var g=function(){return arguments.length};f(’foo’)//=>’fooundefined’g(null,false,undefined)//=>3The arguments keyword is not an array!It just looks like one.In particular,doing any of these will cause problems:arguments.concat([1,2,3])[1,2,3].concat(arguments)arguments.push(’foo’)arguments.shift()To get an array from the arguments object,you can say Array.prototype.slice.call(arguments). As far as I know that’s the best way to go about it.3.2Lazy scoping(a cool thing)Internally,functions use a lexical scoping chain.However,the variables insidea function body aren’t resolved until the function is called.This has some reallynice advantages,perhaps foremost among them self-reference:var f=function(){return f};f()===f//=>true3First-class in the sense that you can pass them around as values at runtime.You can’t reliablyintrospect them,however,because while you can obtain their source code via toString you won’tbe able to access the values they close over.4Note that block scoping isn’t used–the only scopes that get introduced are at function bound-aries.5The number of arguments a function accepts is referred to as its arity.So a unary function,which is monadic,takes one,a binary function,which is dyadic,takes two,etc.A function thattakes any number of arguments is said to be variadic.4Tidbit of pathology:An important consequence of lazy scoping isthat you can create functions that refer to variables that might neverexist.This makes Javascript very difficult to debug.The good partis that Javascript can be made to support syntactic macros via thetoString method:var f=function(){return$0+$1};var g=eval(f.toString().replace(/\$(\d+)/g,function(_,digits){return’arguments[’+digits+’]’}));g(5,6)//=>11(except on IE)Theoretically by extending this principle one could implement truestructural macros,operator overloading,a type system,6or otherthings.3.3The meaning of this(the egregious disaster)One would think it is a simple matter tofigure out what this is,but it’s apparently quite challenging,and Javascript makes it look nearly impossible.Outside of functions(in the global scope,that is),the word this refers to theglobal object,which is window in a browser.The real question is how it behavesinside a function,and that is determined entirely by how the function is called.Here’s how that works:1.If the function is called alone,e.g.foo(5),then inside that function’s bodythe word this will be equivalent to the global object.2.If the function is called as a method,e.g.x.foo(5),then inside thatfunction’s body the word this refers to the object,in this case x.3.If the function starts offas a method and then is called alone:var f=x.foo;f(5);then this will be the global object again.Nothing is remembered aboutwhere f came from;it is all determined right at the invocation site.4.If the function is invoked using apply or call,then this points to what-ever you set it to(unless you try to set it to null or undefined,in whichcase it will be the global object again):var f=function(){return this};f.call(4)//=>4f.call(0)//=>0f.call(false)//=>falsef.call(null)//=>[object global]6God forbid.5Given this unpredictability,most Javascript libraries provide a facility to set a function’s this binding(referred to within Javascript circles as just a function’s binding)to something invocation-invariant.The easiest way to do this is to define a function that proxies arguments using apply and closes over the proper value(luckily,closure variables behave normally):var bind=function(f,this_value){return function(){return f.apply(this_value,arguments)};};The difference between call and apply is straightforward:f.call(x,y,z) is the same as f.apply(x,[y,z]),which is the same as bind(f,x)(y,z). That is,thefirst argument to both call and apply becomes this inside the func-tion,and the rest are passed through.In the case of apply the arguments are expected in an array-like thing(arguments works here),and in the case of call they’re passed in as given.3.3.1Important consequence:eta-reductionIn most functional programming languages,you can eta-reduce things;that is,if you have a function of the form function(x){return f(x)},you can just use f instead.But in Javascript that’s not always a safe transformation; consider this code:Array.prototype.each=function(f){for(var i=0,l=this.length;i<l;++i)f(this[i]);};var xs=[];some_array.each(function(x){xs.push(x)});It might be tempting to rewrite it more concisely as:some_array.each(xs.push);however this latter form will result in a mysterious Javascript error when the native Array.push functionfinds this to be the global object instead of xs. The reason should be apparent:when the function is called inside each,it is invoked as a function instead of a method.The fact that the function started out as a method on xs is forgotten.(Just like case3above.)The simplest way around this is to bind xs.push to xs:some_array.each(bind(xs.push,xs));64GotchasJavascript is an awesome language just like Perl is an awesome language and Linux is an awesome operating system.If you know how to use it properly,it will solve all of your problems trivially(well,almost),and if you miss one of its subtleties you’ll spend hours hunting down bugs.I’ve collected the things I’ve run into here,which should cover most of Javascript’s linguistic pathology.7 4.1Semicolon inferenceYou won’t run into any trouble if you always end lines with semicolons.How-ever,most browsers consider it to be optional,and there is one potential surprise lurking if you choose to omit them.Most of the time Javascript does what you mean.The only case where it might not is when you start a line with an open-paren,like this:var x=f(y=x)(5)Javascript joins these two lines,forming:var x=f(y=x)(5)The only way around this that I know of is to put a semicolon on the end of thefirst line.4.2Void functionsEvery function returns a value.If you don’t use a return statement,then your function returns undefined;otherwise it returns whatever you tell it to.This can be a common source of errors for people used to Ruby or Lisp;for instance, var x=(function(y){y+1})(5);results in x being undefined.If you’re likely to make this slip,there’s an Emacs mode called“js2-mode”that identifies functions with no side-effects or return values,and it will catch most of these errors.87There is plenty of this pathology despite Javascript being generally an excellent language.This makes it ideal both for people who want to get things done,and for bug-connoisseurs such as myself.8Of course,that’s if you’re an Emacs person.If you prefer a real editor(wink),I wrote a custom JS highlighter that handles some cases better than the builtin one:/ spencertipping/js-vim-highlighter.74.3varBe careful how you define a variable.If you leave offthe var keyword,your variable will be defined in the global scope,which can cause some very subtle bugs:var f=function(){//f is toplevel,so global var x=5;//x is local to fy=6;//y is global};As far as I know,the same is true in both types of for loop:for(i=0;i<10;++i)//i is globalfor(var i=0;i<10;++i)//i is local to the functionfor(k in some_object)//k is globalfor(var k in some_object)//k is local to the function4.4Lazy scoping and mutabilityThis is a beautiful disaster.Check this out:var x=[];for(var i=0;i<3;++i)x[i]=function(){return i;};x[0]();//What will these be?x[1]();x[2]();What will our three functions return when they are eventually called?You might expect them to return0,1,and2,respectively,since those were the values of i when they were created.However they will actually all return3.This is because of Javascript’s lazy scoping:Upon creation,each function receives only a variable name and a scope in which to search for it;the value itself is not resolved until the time of invocation,at which point i will equal3.The simplest way tofix this is to wrap our assignment in an anonymous function that is evaluated immediately,introducing another layer of scope.The following code works because within the enclosing anonymous function,the value of new_i never changes.for(var i=0;i<3;++i)(function(new_i){x[new_i]=function(){return new_i;};})(i);By the way,you might be tempted to do this:8for(var i=0;i<3;++i){var j=i;x[j]=function(){return j;};}This won’t work for same reason that our original example failed:j will be scoped to the nearest enclosing function(remember that Javascript’s scoping is function level,not block level!),so its value is changing just as frequently as i’s.4.5EqualityBecause the==is lame,these are all true in Javascript:null==undefinednull==0false==’’’’==0true==1true==’1’’1’==1So,never use the==operator unless you really want this behavior.Instead, use===(whose complement is!==),which behaves sensibly.In particular,=== requires both operands to not only be the same-ish,but also be of the same type. It does referential comparison for boxed values and structural comparison for unboxed values.If one side is boxed and the other is unboxed,===will always return false.Because string literals are unboxed,though,you can use it there:’foo’===’fo’+’o’.Tidbit of pathology:It turns out that==isn’t even stable undertruthiness.If x=0and y=new Number(0),then x==y,!!x isfalse,and!!y is true.Section4.6talks more about why this kindof thing happens.4.6Boxed vs.unboxedBoxed values are always truthy and can store properties.Unboxed values will silently fail to store them;for example:9var x=5;x.foo=’bar’;x.foo//=>undefined;x is an unboxed number.var x=new Number(5);x.foo=’bar’;x.foo//=>’bar’;x is a pointer.9There are other consequences of boxing;see sections4.10and4.11for some examples.9How does a sometimes-boxed value acquire a box?When you do one of these things:1.Call its constructor directly,as we did above2.Set a member of its prototype and refer to this inside that method(seesection5)All HTML objects,whether or not they’re somehow native,will be boxed.4.7Things that will silently fail or misbehaveJavascript is very lenient about what you can get away with.In particular,the following are all perfectly legal:[1,2,3].foo//=>undefined[1,2,3][4]//=>undefined1/0//=>Infinity0*’foo’//=>NaNThis can be very useful.A couple of common idioms are things like these: e.nodeType||(e=document.getElementById(e));options.foo=options.foo||5;Also,the language will convert anything to a string or number if you use+. All of these expressions are strings:null+[1,2]//=>’null1,2’undefined+[1,2]//=>’undefined1,2’3+{}//=>’3[object Object]’’’+true//=>’true’And all of these are numbers:undefined+undefined//=>NaNundefined+null//=>NaNnull+null//=>0{}+{}//=>NaNtrue+true//=>20+true//=>1And some of my favorites:null*false+(true*false)+(true*true)//=>1true<<true<<true//=>4true/null//=>Infinity104.8Things that will loudly failThere is a point where Javascript will complain.If you call a non-function, ask for a property of null or undefined,or refer to a global variable that doesn’t exist,10then Javascript will throw a TypeError or ReferenceError.By extension,referring to local variables that don’t exist causes a ReferenceError, since Javascript thinks you’re talking about a global variable.4.9Throwing thingsYou can throw a lot of different things,including unboxed values.This can have some advantages;in this code for instance:try{...throw3;}catch(n){//n has no stack trace!}the throw/catch doesn’t compute a stack trace,making exception processing quite a bit faster than usual.But for debugging,it’s much better to throw a proper error:try{...throw new Error(3);}catch(e){//e has a stack trace,useful in Firebug among other things}4.10Be careful with typeofBecause it behaves like this:typeof function(){}//=>’function’typeof[1,2,3]//=>’object’typeof{}//=>’object’typeof null//=>’object’typeof typeof//hangs forever in Firefox typeof is a really lame way to detect the type of something in many cases.11 Better is to use an object’s constructor property,like this:10To get around the error for this case,you can say typeof foo,where foo is the potentially nonexistent global.It will return’undefined’if foo hasn’t been defined(or contains the value undefined).11And because it returns a string,it’s marginally slower than using.constructor.11(function(){}).constructor//=>Function[1,2,3].constructor//=>Array({}).constructor//=>Objecttrue.constructor//=>Booleannull.constructor//TypeError:null has no properties In order to defend against null and undefined(neither of which let you askfor their constructor),you might try to rely on the falsity of these values:x&&x.constructorBut in fact that will fail for’’,0,and false.The only way I know to get around this is to just do the comparison:x===null||x===undefined?x:x.constructorAlternatively,if you just want tofind out whether something is of a given type,you can just use instanceof,which never throws an exception.124.11Also be careful with instanceofinstanceof is generally more useful than typeof,but it only works with boxed values.For example,these are all false:3instanceof Number’foo’instanceof Stringtrue instanceof BooleanHowever,these are all true:[]instanceof Array({})instanceof Object[]instanceof Object//Array inherits from Object/foo/instanceof RegExp//regular expressions are always boxed (function(){})instanceof FunctionOne way to work around thefirst problem is to wrap primitives:new Number(3)instanceof Number//truenew String(’foo’)instanceof String//also truenew Boolean(true)instanceof Boolean//also true In general,(new x.constructor(x)instanceof x.constructor)will be true for all primitive x.However,this doesn’t hold for null or undefined. These will throw errors if you ask for their constructors,and as far as I knoware never returned from the result of a constructor invocation(using new,that is).12Well,almost.If you ask for it by putting null,undefined,or similarly inappropriate things onthe right-hand side you’ll get a TypeError.124.12Browser incompatibilitiesGenerally browsers since IE6have good compatibility for core language stuff. One notable exception,however,is an IE bug that affects String.split:var xs=’foo bar bif’.split(/(\s+)/);xs//on reasonable browsers:[’foo’,’’,’bar’,’’,’bif’] xs//on IE:[’foo’,’bar’,’bif’]A more subtle bug that took me several hours tofind is that IE6also doesn’t return functions from eval():var f=eval(’function(){return5}’);f()//on reasonable browsers:5f()//on IE6:’Object expected’(because f is undefined) I’m sure there are other similar bugs out there,though the most common ones to cause problems are generally in the DOM.135PrototypesI used to have a very anti-OOP comment here,but considering that I occa-sionally use prototypes I removed it.Despite my obvious and probably unfair vendetta against Javascript’s linguistic compromises to pander to Java-inspired marketing pressure,14prototype-based programming can be useful on occasion. This section contains my subjective and biased view of it.Whenever you define a function,it serves two purposes.It can be what every normal programmer assumes a function is–that is,it can take valuesand return values,or it can be a mutant instance-generating thing that does something completely different.Here’s an example://A normal function:var f=function(x){return x+1};f(5)//=>6This is what most people expect.Here’s the mutant behavior that no rational person would ever imagine://A constructor functionvar f=function(x){this.x=x+1};//no return!var i=new f(5);//i.x=6The following things are true at this point:13jQuery is your friend here.It’s branded as a Javascript library,but in fact it’s a set of enhance-ments to the DOM to(1)achieve a uniform cross-browser API,and(2)make it easier to retrieveand manipulate nodes.14Hence its name,Java script,despite all of the dissimilarities.13i.constructor===fi.__proto__===i.constructor.prototype//on Firefox,anywayi instanceof ftypeof i===’object’The new keyword is just a right-associative(prefix)unary operator,so youcan instantiate thingsfirst-class:var x=5;new x.constructor();//Creates a boxed version of x,regardless of what x is new new Function(’x’,’this.x=5’);If you are going to program using this questionable design pattern,thenyou’ll probably want to add methods to things:15var f=function(x){this.x=x};f.prototype.add_one=function(){++this.x};var i=new f(5);i.add_one();i.x//=>6You canfind tons of information about this kind of prototype programmingonline.5.1Why new is awfulnew has some cool features(such as beingfirst-class),but it has a really horribleshortcoming.Most functions in Javascript can be forwarded–that is,you canwrite a new function to wrap an existing one and the function being called willnever know the difference.For example:var to_be_wrapped=function(x){return x+1};var wrapper=function(){return to_be_wrapped.apply(this,arguments);};//for all x,wrapper(x)===to_be_wrapped(x)However,new has no such mechanism.You can’t forward a constructor inthe general case,because new has no equivalent of apply.(Though this isn’t thewhole story–see section7.1for a way hack to do it.)15This section used to say that i.x would evaluate to7.That isn’t true though.It’s actually6,asindicated.(Thanks to Daniel Gasparotto for pointing this out.)145.2Why you should use prototypesIf you need a dynamic-dispatch pattern,then prototypes are probably your best bet and you should use them rather than a roll-your-own approach.Google’s V8 has a bunch of prototype-specific optimizations,as do later releases of Firefox. Also,prototypes save memory;having a pointer to a prototype is much cheaper than having n pointers to n attributes.If,on the other hand,youfind yourself implementing actual inheritance hierarchies,then you’re probably making a mistake.16I have found prototypes to be an effective way to program in Javascript,but inheritance in Javascript is (1)slow,17and(2)poorly representative of Javascript’s“everything is public”model.5.3AutoboxingYou might be tempted to try something like this:18Boolean.prototype.xor=function(rhs){return!!this!==!!rhs};And,upon running this code,you’d run into this tragically unfortunate property:false.xor(false)//=>trueThe reason is that when you treat an unboxed value as an object(e.g.invoke one of its methods),it gets temporarily promoted into a boxed value for the purposes of that method call.This doesn’t change its value later,but it does mean that it loses whatever falsity it once had.Depending on the type you’re working with,you can convert it back to an unboxed value:function(rhs){return!!this.valueOf()!==!!rhs};6A Really Awesome EqualityThere is something really important about Javascript that isn’t at all obvious from the way it’s used.It is this:The syntax foo.bar is,in all situations, identical to foo[’bar’].You could safely make this transformation to your code ahead of time,whether on value-properties,methods,or anything else. By extension,you can assign non-identifier things to object properties:16OK,I’m being biased about this point.I tend to treat Javascript more like Scheme than like Smalltalk,so I don’t think much in terms of classical object-oriented modeling.Also,since closures are really fast,it’s OK to use functional abstraction instead of inheritance.Javascript tends to be better suited to metaprogramming than inheritance.17In some cases really slow.The difference between single-level and multiple-level prototype lookups in Firefox3.5,for instance,is enormous.18!!x is just an idiom to make sure that x ends up being a boolean.It’s a double-negation,and !always returns either true or false.15var foo=[1,2,3];foo[’@snorkel!’]=4;foo[’@snorkel!’]//=>4You can also read properties this way,of course:[1,2,3][’length’]//=>3[1,2,3][’push’]//=>[native function]In fact,this is what the for(var...in...)syntax was built to do: Enumerate the properties of an object.So,for example:var properties=[];for(var k in document)properties.push(k);properties//=>a boatload of stringsHowever,for...in has a dark side.It will do some very weird things when you start modifying prototypes.For example:Object.prototype.foo=’bar’;var properties=[];for(var k in{})properties.push(k);properties//=>[’foo’]To get around this,you should do two things.First,never modify Object’s prototype,since everything is an instance of Object(including arrays and all other boxed things);and second,use hasOwnProperty:19Object.prototype.foo=’bar’;var properties=[],obj={};for(var k in obj)obj.hasOwnProperty(k)&&properties.push(k); properties//=>[]And very importantly,never use for...in to iterate through arrays(it returns string indices,not numbers,which can cause problems)or strings. Either of these will fail if you add methods to Array or String(or Object,but you shouldn’t do that).7If You Have20Minutes...Javascript can do almost anything that other languages can do.However,it might not be very obvious how to go about it.19OK,so you’re probably wondering why we don’t see the hasOwnProperty method from a for ...in loop,since it’s obviously a property.The reason is that Javascript’s attributes have invisible flags(as defined by the ECMAScript standard),one of which is called DontEnum.If DontEnum is set for some attribute,then a for...in loop will not enumerate it.Javascript doesn’t provide a way to set the DontEnumflag on anything you add to a prototype,so using hasOwnProperty is a good way to prevent looping over other people’s prototype extensions.Note that it fails sometimes on IE6;I believe it always returns false if the prototype supplies an attribute of the same name.167.1Forwarding constructorsI mentioned earlier that constructors can’t be forwarded.That isn’t exactly true.You can use this egregious hack(which is actually kind of beautiful in a don’t-try-this-at-home sort of way):20var ctor=...;//we want to wrap thisvar wrapper=function(){var params=/ˆfunction\s*\(([ˆ)]*)\)/.exec(ctor.toString());if(params){var unlikely=’_’+(Math.random()<<20).toString(36);eval(’var’+unlikely+’=ctor;’);var f=eval(//fails on IE6’function(’+params[1]+’){’+’return new’+unlikely+’(’+params[1]+’);’+’}’);return f.apply(this,arguments);}};Now you can say wrapper(x,y,...)and it will be translated into new ctor(x,y,...)–and because wrapper is just a regular function,you can call its apply method to give it an array of arguments.7.2Iterators for cool peopleBecause languages like Ruby showed the world just how pass´e for loops really are,a lot of self-respecting functional programmers don’t like to use them.If you’re on Firefox,you won’t have to;the Array prototype includes map and forEach functions already.But if you’re writing cross-browser code and aren’t using a library that provides them for you,here is a good way to implement them:Array.prototype.each=Array.prototype.forEach||function(f){ for(var i=0,l=this.length;i<l;++i)f(this[i]);return this;//convenient for chaining};Array.prototype.map=Array.prototype.map||function(f){ var ys=[];for(var i=0,l=this.length;i<l;++i)ys.push(f(this[i]));return ys;};20In general,anytime you run into something that’s“impossible”in Javascript,you have a technique hack at your disposal.The sledgehammer is eval,which lets you do anything.17。

相关文档
最新文档