(no96) ============================================================================================= view-source:http://...可以查看网页源代码 =============================================================== 让script以不同于主页面的编码载入: <script src='http://...' charset='gb2312'></script> =============================================================== html元素的onclick字串内引号多重嵌套: (最多五重):"...'...\'...\u0022...\u005C\u0022...\u005C\u0022...\u0022...\'...'..." (从第二重开始就不允许换行了) javascript内引号多重嵌套: ... =============================================================== <iframe id=sf src="kk.htm"></iframe> (从网络执行时src只能为源服务器文件) 只有等到sf初始化完成,才能执行读取操作,否则会报告对象不存在: <script> function kk() { try { t=sf.document.body.innerText;alert(t);//得到框窗内文字. h=sf.document.body.innerHTML;alert(h);//得到框窗内源代码. } catch(e) {setTimeout("kk()",1000);}; } kk(); </script> =================================================== 用innerHTML往span内写字串时, 字串内每行的最后一个字符都应加"\", 否则会报错字串未结束: logon_form.innerHTML='<form action="logon.php" method="post">\ <table width="140" height=="70" border="0" cellpadding="0" cellspacing="0">\ ... '; =================================================== 网页跳转用window.location="...",window.location.href="...",或document.URL="...". 检查一个窗口的location不要用window.location, 因其等价于window.location.href(含传输协议、主机和传递参数), 应该用window.location.pathname(不含传输协议、主机和传递参数). window.location.href==window.location.protocol+'//'+window.location.host+window.location.port+ window.location.pathname+window.location.search+window.location.hash; ===================================================================================== 如果用:<a href="a.htm?page=3">下一页</a>链接不能刷新页面, 这样是没有用的,还没赋值好可能就刷了:<a href="javascript:location='a.htm?page=3';location.reload();">下一页</a> 这样也是没有用的,htm后参数不同ie不认为是不同url:<a href="javascript:location='a.htm?page=3'+'&'+Math.random();">下一页</a> 这么解决,在a.htm里加上: <script> if (window.name) {window.name=""; window.location.reload(); } else {window.name="board"; } </script> ===================================================================================== html页面间传递参数(只不过在ie下, utf-8中文参数都被转成了gbk): <a href="?kkk=999&kk=888">dfsf</a> <script> document.write(window.location.search.match(/(\?|&)kk\=(.+?)(&|$)/)[2]); </script> ====================================================== 链接的target是指向窗口name,而不是窗口id(用于javascript) ==================================================== return window.confirm('确认删除吗?') //根据"确认"/"取消"按钮传回真假值 ==================================================== 所有javascript实现的跳转是跟踪不到document.referrer(HTTP_REFERER)的,但 iframe内的javascript会被跟踪到母窗口URL当作referrer. ================================================= 相等比较符:==(字串比较还是用==) 严格相等比较符:=== 字串连接符:+ =================================================== <iframe id=sf src="kk.htm"></iframe> <script> sf.document.write("hell");//往框窗内覆写代码,而非附加显示 sf.document.write("\<script\>window.location='hell.htm'\<\/script\>"); sf.document.close();//避免框窗的死循环 </script> ================================================== setTimeout("document.write('hello')",0)覆写了源代码,查看源代码只剩下'hello', 而不是像document.write只附加显示,如果想附加代码可以先定义<div id=mydiv></div>, 然后再mydiv.innerHTML='hello'; =================================================== 要清除显示而不覆写代码可以用document.body.innerHTML=''. 但是里面的javascript要写成" <script defer>alert('hello');</script>" 或"<"+"script>"+"..."+"</script"+">" 或unescape("%3cscript%3edocument.write('hello')%3c/script%3e") 注意"<script defer>"前的" "不能省略 如果放在网站上" <script defer src='test.js'><script>"则test.js不执行(如果不用innerHTML而用document.write则没问题), 打开页面后再点一次转到按钮倒是能执行. ====================================================================================================== ht = new ActiveXObject("Microsoft.XMLHTTP"); ht.open("GET", "http://www.time.ac.cn/timeflash.asp?user=flash", false); //可以选择用GET或POST方式,及目标地址,及是否异步(并发执行后面的代码,就不是直接responseText了,要用onreadystatechange) //ht.setRequestHeader("Referer","http://www.time.ac.cn/IMG/DigitalClock.swf"); //可以伪造Referer ht.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//POST时这句必需 ht.send(""); //send中可以加上要Get或Post的字串,如:"select=All&for=The Usual Suspects" r = ht.responseText; --可以读远程文件,由于ie修补了漏洞(xmlhttp不再只是检验头部传输协议),用php语句 header("Location:file://c:/skin.txt")已经不能欺骗它,只能得到test.php本页的html源码. 这段代码写在本地有效,写在服务器上竟说没有权限了. xmlhttprequest能自动往ie种上收到的同域session id, 也能自动送出ie已种的同域phpsessid xmlhttprequest跟flash一样"只能打电话回家", 不能进行跨域访问, 除非用同站的php代理 ====================================================================================================== ajax登录discuz: ClearCookie(); ht=getXMLRequester(); ht.open('POST', 'http://oralb-professional.com.cn/disc/logging.php?action=login', true); ht.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); ht.send("referer=index.php&loginfield=username&questionid=0&cookietime=0&loginsubmit=1" +"&username="+document.getElementById('username').value+"&password="+document.getElementById('password').value ); =================================================== js_pxy.php可以用这个取代(注意要用串行方式): <script>XMLHttp.sendReq('GET', 'logon_form.php', '',false, 'document.write(objXMLHttp.responseText);');</script> =================================================== 登录块常用ajax: //head内: <script type="text/javascript" src="js/xmlhttp.js"></script> <script type="text/javascript" src="js/cookie.js"></script> <script> function logon_refresh() {XMLHttp.sendReq('GET', 'logon_form.php', '',true, 'document.getElementById("logon_span").innerHTML=objXMLHttp.responseText;'); } function logon() {XMLHttp.sendReq('POST', 'logon.php', 'username='+logon_form.username.value+'&password='+logon_form.password.value,true, 'if (objXMLHttp.responseText!="ok") {alert(objXMLHttp.responseText);} else {logon_refresh();}'); } function logout() {ClearCookie();logon_refresh(); } </script> //登录块: <span id="logon_span"> </span> <script type="text/javascript">logon_refresh();</script> =================================================== "A".charCodeAt(0)等价于php里的ord("A");String.fromCharCode(65)等价于php里的chr(65) ==================================================== javascript内再写javascript: <script> for (i=0;i<3;i++) { document.write("\<script\>document.write('hello!');\<\/script\>"); } </script> ===================================================== 有间隔时间,有终止条件循环(flag为终止条件), 由于javascript里没有sleep或wait函数, 而且while循环也不能拦住其后语句的执行, 最终只能如下实现(用setInterval配合clearInterval也应该能实现): function kk() { ... if (!flag) {setTimeout("kk()",5000); } else {... } } kk(); ========================================================= time=new Date();time.setTime(time.getTime()+24*60*60*1000); 或new Date((new Date()).getTime()+24*60*60*1000); 再document.cookie="counter=4;expires="+time.toGMTString(); 必须有expires才有效. 修改的时候只要document.cookie="counter=7";即可. 设置cookie时document.cookie="counter=7; path=/;"+time.toGMTString();就使该页cookie为全站可用 清空所有cookie: while (document.cookie!='') {document.cookie=document.cookie+";expires=Thu, 1 Jan 1970 00:00:00 UTC";} 清除指定cookie: document.cookie = name + "=;path=/;"; 这样不会清空子目录下的cookie ============================================================ 要生成不重复的字串不要用Math.random(), 这样(打响指最高记录8次/秒,假设最快按10次鼠标): Math.round(new Date().getTime()/100).toString().slice(-5), 这样可以保证一两个小时内人工操作数不重复. ============================================================ javascript:document.write((new Date("2004/4/1 00:00:00")-new Date("2004/3/29 00:00:00"))/24/60/60/1000); javascript:document.write((new Date("2004/4/1")-new Date("2004/3/28"))/24/60/60/1000); javascript:document.write(68286+(new Date(new Date().getFullYear()+"/"+(new Date().getMonth()+1)+"/"+new Date().getDate())-new Date("2003/7/13"))/24/60/60/1000); 显示出两日的日数差. ============================================================ 在文件末尾写上<noscript><script>只能跟后面的一段<script>...</script> 抵消,所以最好用<title>作尾来抵消免费服务器添加的广告. ============================================================= eval("document.write('kkk');")返回的结果是kkk. ============================================================= 破解1dnn.com的加密网页其实很简单,只要添加<iframe id=d></iframe>,然后将第一个函数解码, 将其中的document.write改为d.document.write即可,网页源代码都还原到iframe中了. (在倒第23个%(即%64%6f%63之)前写上%64%2e) =============================================================== <img src="javascript:eval('alert(\'nsfocus\');alert(\'czy\')')">这个链接居然也允许执行 ======================================================================= 解析php的setcookie种下的utf-8中文cookie: 用unescape(decodeURI(document.cookie.substring(offset, endstr))) 实际上decodeURIComponent()能取代unescape(decodeURI()), 但这对setcookie种下的gbk中文cookie无效, 除非用setrawcookie来种gbk中文cookie ======================================================================= encodeURI对中文进行的是unicode编码:一个GBK变成3个%字节,两个utf-8变成9个%字节(奇数个utf-8报错), 而escape:一个GBK变成1个%u字节,两个utf-8变成3个%u字节(奇数个utf-8报错), 都不同于php里的rawurlencode:一个GBK变成2个%字节,两个utf-8变成6个%字节. decodeURI倒是可以解码rawurlencode编码的中文 ======================================================================= 模仿php的htmlspecialchars: htmlspecialchars(str) {return str.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<") .replace(/>/g, ">").replace(/'/g, "'"); } 在innerHTML=或document.write()需要输出为非html字串(比如代码展示)的时候可能用到. ======================================================================= unescape的真正反函数不是escape(空格,大部分符号,多字节字符),而要用str.charCodeAt(i)求得str每个字符的 十进制序号,还要将十进制换十六进制,整个函数可以取名UrlEncode. var qswhU2GB=[];//Unicode和GB的对应表,略 function UrlEncode(str){ var i,c,ret="",strSpecial="!\"#$%&'()*+,/:;<=>?@[\]^`{|}~%"; for(i=0;i<str.length;i++){ if(str.charCodeAt(i)>=0x4e00){ c=qswhU2GB[str.charCodeAt(i)-0x4e00]; ret+="%"+c.slice(0,2)+"%"+c.slice(-2); } else{ c=str.charAt(i); if(c==" ") ret+="+"; else if(strSpecial.indexOf(c)!=-1) ret+="%"+str.charCodeAt(i).toString(16); else ret+=c; } } return ret; } ======================================================================= unescape的真正反函数: function escape_total(str) { str_esc = escape(str); rtn = ""; lng = str_esc.length; for (i=0;i<lng;++i) { if (str_esc.charAt(i)=="%") { rtn = rtn + str_esc.substr(i,3); i = i + 2; } else { rtn = rtn + "%" + str_esc.charCodeAt(i).toString(16).toUpperCase(); } } return rtn; } ======================================================================= 800*600显示IE5最大化窗口下: Body默认左边距10(相当20象素),网页中表或图片(边框宽0)的完全显示的最大宽度759. Body左边距定为0,网页中表或图片(边框宽0)的完全显示的最大宽度779. Body左边距定为0,无垂直滚动条(宽17象素),网页中表或图片(边框宽0)的完全显示的最大宽度796. ======================================================================= 对象的隐藏与显示: obj.style.display="none";(用''显现) //隐藏对象,让出位置 obj.style.visibility="hidden";(用"visible"显现) //隐藏显示,不让出位置 obj.disabled=true; //灰显、只读、不提交数据 obj.readOnly=true; //亮显、只读、提交数据 要让一个对象真正无效最好是用:obj.style.display="none";obj.disabled=true; ======================================================================= 重载一个onclick事件: <input type=button onclick="alert('xx')" id="xx" value="xx"> <input type=button onclick="xx.onclick=function() {alert('kk');}" value="kk"> 注意:是"=function()"或"=function anonymouse()",不是"='function()". 这样的直接定义函数也可指定参数: var fun=function(var1){alert(var1);} fun('hell'); ======================================================================== 对于特殊字元不必记忆其名称(如:<)仅需"<".charCodeAt(0)出序号,然后&#序号 ============================================================================ html:table之内tr之间的杂代码在ie中解析时会解析到整个table之前 ======================================================================== 弹出窗口刷新源窗口: opener.location=opener.location;或opener.location='http://...'; 但更可靠的方法是window.open('http://...', 'window_list');(源窗口已window.name=window_list) 因源窗口可能已经改变过页面(前者无效),或者已经关闭(前后者皆无效), 不要采用opener.location.reload();因源窗口有可能是有提交数据的,会弹出是否重发数据的安全预警, 不过这时window.open也不好,如果原窗口是搜索列表页面,需要将搜索条件串到open链接上,可用提交opener的翻页表单的方法 当关闭弹出窗口时应将源窗口置顶window_list=window.open('http://...', 'window_list');window_list.focus(); ======================================================================= window.open可以跨网站target窗口 空串窗口名不作为窗口指针,等同于'_blank' ======================================================================= windows:a,login,b,c a opens login, login calls opener and self as a,login login changes self's name as b(by user's click) c opens b, b calls opener and self as a,login(keeps opener as a(not c),changes self as login) 即自己改名过的弹出窗口在被引用过一次以后就恢复了原来的名字(如果原来没有名字则还是自己的命名); window.open如果指向的是已经存在的窗口则不会改变该窗口的opener.name 页面跳转不存在上面的问题: windows:a,login,b,c a(a.htm set self'name as a) jump to login(login.htm calls self's name as a) login change self's name as b(by user's click) c opens b, b calls self as b ======================================================================= 首页常用body配置:<body topmargin="0" leftmargin="0" scroll="no"> 并不能在body中直接配置页面尺寸和位置,可以用onload="window.moveTo(200, 50);window.resizeTo(600, 600);" ie中不能控制statusbar,locationbar,menubar的visible属性 想要主页全屏可以用window.open(),然后关闭登录窗口的办法(window.opener=null;window.close();) ========================================================================= window.onload事件是指整个页面完全解析后再触发 ========================================================================= 新开一个窗口window.open('http://...', '', 'height=600,top=50,left=200,width=600,scrollbars=yes'); 新开一个全屏窗口window.open('http://...', '', 'fullscreen=yes'); 弹出窗口重开主窗口window.open('http://...', 'window_list', 'menubar=yes,toolbar=yes,location=yes,resizable=yes'); 或window.open('http://...', 'window_list'); 如果要在链接中使用window.open则要使用void运算符以返回undefined: <a href="javascript:void(window.open( ));">Open New Window</a> 或者: <a href="javascript:window.open( );void 0;">Open New Window</a> ============================================================= 要从弹出窗口用target提交表单到主页面,可以先opener.name=openerWindow,或者在主页面内window.name=openerWindow, 然后在target后就可以用openerWindow了,"opener"是窗口指针,"openerWindow"是窗口名,不同于window内 的frame或iframe,它们的窗口名同时也是窗口指针,要在源窗口中获得弹出窗口的指针,可以: opened=window.open('','childWindow'),或者在弹出窗口时就opened=window.open('http://...', 'childWindow','...') 要获得target窗口的指针也是用target=window.open('','targetWindow')的方法 ================================================================================= 当需要从源窗口提交表单到弹出窗口时,必须先创建弹出窗口名(弹出窗口内window.name=或window.open()), 而主窗口再次提交数据到该弹出窗口时,在ie下,弹出窗口刷新了但并没有置顶,一个解决方法是在弹出窗口内window.focus(); 当需要从源窗口提交表单到弹出窗口又要控制弹出窗口的尺寸,只好在window.open内用url字串传数据 =================================================================================== 将对象转换成字串:(String)anObject;或anObject.toString(); =================================================================================== 后退可以用history.go(-1);或history.back(); =================================================================================== 检查一个变量是否存在要用"window."否则会被当成"document.": <script> //kkk="kkk"; if (!window.kkk) document.write("hello");else document.write(kkk); </script> ================================================================================ 取得checkbox或radio的选值要使用循环(设值只需checkbox/radio[n].checked=true), 取得select的选值只须:aSelect.value 也可以aSelect.options[aSelect.selectedIndex].value, 当aSelect.options.length==0时,aSelect.selectedIndex恒为-1; 执行aSelect.options[2].selected=true;界面发生变动,原selected的自动变成false; 其实select的value也可以读写,读出选中的option的值,写入自动选上值匹配的option,不匹配则加空option. 销毁select内的option方法:for (i=aSelect.length-1;i>=0;--i) {aSelect.options[i]=null;} 新建option方法:aSelect.option[0]=new Option(aText,aValue); 销毁或新建后最好用history.go(0)来刷新呈现 销毁html元素用ele.outerHTML=''的方法 (除了td,tr不能这么销毁,用ele_tr.deleteCell(the_cell.cellIndex),ele_tb.deleteRow(the_row.rowIndex)) ================================================================================ 即使是radio或checkbox,如果只有一个就不被当作数组,使用length得不到个数,只有使用自己定义的ArrLen函数 ================================================================================= 有时一些input不需要提交,可以采用不设name的方法,唯有radio不设name在ie中会出现无法选上的问题 ================================================================================= 让弹出窗口恒置顶:<body onblur="window.focus();"> ================================================================================= parentElement相对于children,例:tb_fr.rows[0].cells[1].children[0].value aInput.parentElemtent可能是其所在paragraph或font(可以使用.tagName获知), aCell.parentElement是其所在row,aRow.parentElement是其所在tbody,aTBody.parentElement是其所在table 可以分别用aRow.rowIndex和aCell.cellIndex获取行次和列次. ================================================================================= javascript的函数的输入参数似乎是直接传址的,将页面对象传进去,可以在函数内直接操作该页面对象, return传出也是传址的,传出的对象仍是页面对象,可以在外面直接操作. 例: function ArrEle(anElementArray,No)//将数组型页面元素统一当作数组使用,以避免只有一个元素时转回了普通元素 { if (anElementArray[0]) { if (No<anElementArray.length) return anElementArray[No]; } else { if (No==0) return anElementArray; } } ================================================================================= aString.slice(index_start,index_after_end) //index_start:0|起位,-1|末位;index_after_end:0|起位,省略或正超位|当末后,-1|末位,负超位|当0起位 aString.substr(index_start,length) //index_start:0|起位,负数|当零,正超长|当末;length:省略或超长|当末长,负数|当零 aString.substring(index_start,index_after_end) //index_start:0|起位,负数|当作零;index_after_end:0|起位,省略或正超位|当末后,负数|当零 显然slice可以取代substring,建议只用slice和substr(两个功能合起来才相当于php的substr) ================================================================================= 搜索子串:aString.indexOf(str_needle);没找到返回-1. ================================================================================= ["2005","6","8"].join("-");得到字串"2005-6-8", 而"2005-6-8".split("-");得到数组["2005","6","8"]. ================================================================================= 既保留select的选项又让用户不能改变选值的一个方法是: <select name=aSelect onchange="for (i=0;i<this.options.length;++i) {if (this.options[i].defaultSelected) this.options[i].selected=true;}"> 要控制选值时可用:aSelect.options[index_change_to].defaultSelected=true;aSelect.options[index_change_to].selected=true; 但是最好还是浏览器标准中能给select添加一个readonly属性,以使其既保留选项又无法下拉(展开). ===================================================================================== 运算符优先顺序(高到低):算术运算 > 比较运算 > 逻辑运算 ===================================================================================== switch (expression) { case 1: break; case 2: break; default: } ===================================================================================== var aObject = {x:1,y:2,z:3}; var aArray = [1,2,3];//new Array(1,2,3); document.write({x:1,y:2,z:3}.y); document.write([1,2,3][1]); ===================================================================================== aOjbect={ele_1:1,ele_2:2,ele_red:3};然后使用eval('aOjbect.ele_'+key)来访问这个对象的元素, 看起来就是这个对象既可以使用字母元素名,也可以使用数字元素名了. ===================================================================================== 获得标准日期: function Pad(str,chr,no,left) { for (i=0;i<no-str.length;++i) { if (left) { str=chr+str; } else { str=str+chr; } } return str; } dt_std=Pad((String)(new Date().getFullYear()),'0',4,1)+'-' +Pad((String)(new Date().getMonth()+1),'0',2,1)+'-' +Pad((String)(new Date().getDate()),'0',2,1); ===================================================================================== 三十六进制计时法: dt=new Date(); yr0=Math.floor(dt.getFullYear()/100);yr1=dt.getFullYear()%100;mn=dt.getMonth()+1;dd=dt.getDate(); mydt=yr0.toString(36)+yr1.toString(36)+mn.toString(36)+dd.toString(36); ===================================================================================== <input type="button" value="打印" onclick="this.style.display='none';window.print();window.close();"> 打印串口时隐藏按钮,打印开始后关闭窗口 ===================================================================================== 直接打印: <OBJECT classid='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2' height='0' id='WebBrowser' width='0'> </OBJECT> <INPUT name='Button' onclick='document.all.WebBrowser.ExecWB(6,6)' type='button' value='直接打印'> ===================================================================================== 自动最大化窗口: <object id="Max" classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"> <param name="Command" value="Maximize"><!--Minimize,Close--> </object> <script>if (document.body.offsetWidth<screen.width) {Max.Click();}</script> 使用这个在本地有安全提示(在远端则无效), 在本地Maxthon有效 <script>top.moveTo(0,0);top.resizeTo(screen.availWidth,screen.availHeight);</script> 在本地和远端都有效, 无安全提示, 但在Maxthon中无效 ===================================================================================== 设置首页及添加收藏: window.style.behavior='url(#default#homepage)';window.setHomePage('http://minzheng.xh.sh.cn'); window.external.addFavorite('http://minzheng.xh.sh.cn','上海市徐汇区民政局'); ===================================================================================== 在事件处理内获取事件源:window.event.srcElement, (点击一个格子内的元素可以触发其所在行的点击事件,直接触发对象是行,触发源仍是该元素,如果点击这个元素的旁边, 则直接触发对象是行,触发源是格子,因而事件处理函数内使用触发源作为参照来定位其它元素是不稳定的, 还是要使用触发对象来参照,这就不得不通过参数this将触发对象传进去) 若想在弹出窗口中获取主窗口的弹出事件源,可以在主窗口中window.evnSrcEle=window.event.srcElement, 然后在弹出窗口中用opener.evnSrcEle访问: <input type="text" name="product_num_tmp" size="18" readonly onfocus="window.evnSrcEle=window.event.srcElement;this.blur();window.open('<?echo $ROOTPATH;?>/ui/CommonPage/pop_up/product.php','pop_up_product','height=500, top=100, left=250, width=500, scrollbars=yes');"> ===================================================================================== iframe内可以用window.parent.aFunction()来访问父窗口的aFunction函数 ===================================================================================== 查看一个对象的所有属性: <input type=text id="a" value="30"> <SCRIPT> for(i in a)document.write(i+" = "+a[i]+"<br>") </SCRIPT> ===================================================================================== text、select等的onchange触发指的是用户手工操作,js的操作不会触发onchange,可以使用onpropertychange, 如果要求手工操作过程中触发则用onkeypress. ===================================================================================== 对于大数据量的表单, 不应该在最后提交的时候再检查数据合法性,而是onblur时检查 (不用onchange, 因为检查发现非法时要恢复原数据, 而onchange不认为数据已恢复, 再次输入相同非法数据时不触发onchange): <script> var valid=true; function check(obj) {if(obj.value==''){valid=false;alert('不合XML规则');obj.focus();}else{valid=true;} } </script> <input type="text" value="<?=$key?>" size="<?=strlen($key)?>" onblur="check(this)"> 在提交的地方如action里要检查valid变量 ===================================================================================== 在ie下,如果form的method没有定义post,则action里?后的参数被忽略了,form里的元素被添加到?后作get参数 ===================================================================================== button不像submit button,是不提交数据的 ===================================================================================== 直接在form的action放上javascript,这样onsubmit上的判断(return undefinded;或return;)和submit改成普通按钮弹出窗 口都可以写在action的javascript里了,在输入框内按回车也能正常触发表单提交了(the_form.action='trg.php';the_form.submit();) ===================================================================================== 调试表单检查时, 可以在onsubmit里这样写:check();return false; ===================================================================================== 无提示关闭窗口: window.opener=null;window.close(); 另外,在弹出窗口中即使只用window.close();也不会有关闭警报 总之只有当window.opener==undefined时才被认为不安全而有关闭警报 ===================================================================================== 三个概念: 未定义变量,读取它会报错,可以这样判断:typeof(flg)=="undefined",也可以try{flg;}catch(e){is_assigned=false;} 值为undefined的变量,实际上就是unassigned(未赋值)变量 值为null的变量,即被赋值为空对象的变量 ===================================================================================== <head> <style> table {font-size:9px;} </style> </head> <!-- 如果style段后面没有载入css文件覆盖定义,则可如下动态改变网页样式: --> <body> <button onclick="document.styleSheets[0].cssText='table {font-size:18px;}';" type="button">改变样式</button> </body> ===================================================================================== 可以配合表单输入检查函数集进行输入检查: <script> function check() { errstr=""; items=[ ['md5','IsBlank','文件的MD5编码字串不能为空'], ['retail','!IsFloat','零售价格应是数字'], ['email','!IsEmail','电邮格式不正确'] ]; for (i=0;i<items.length;++i) { if (eval(items[i][1]+"(form_add."+items[i][0]+".value);")) { errstr=errstr+items[i][2]+",\n\r"; } } if (errstr!="") { alert(errstr+"请修改后再提交。"); return false; } return true; } </script> ===================================================================================== 使用office附带的mse7.exe(可以通过word下"工具\宏\Microsoft脚本调试器"安装,并安装上web调试器)可以 非常方便地调试客服端脚本(通过开启ie高级下的允许脚本调试并选中"查看\脚本调试程序\在下一条语句中断" 并刷新网页), 有的机器要每次调试前要先开启mse7附着ie进程, 然后才能从ie由"在下一条语句中断"触发 用firefox调试报错非常准, 有venkman调试器. ===================================================================================== 十六进制与十进制相互转换: myDec=parseInt(myHex,16); myHex=myDec.toString(16).toUpperCase(); 十进制字串转整数: aInt=Number(str_int); 更复杂的字串转整数: aInt=parseInt(str_int); ===================================================================================== 不想额外送出数据时,可以将用户操作表单(form_opr)和提交表单(form_send)分开: <script> function handle() { ... form_send.submit(); } </script> <form name="form_send" method=post action="http://..."> <input name="loc" type="hidden"> </form> <form name="form_opr" action="javascript:handle();"> <input name="loc" value="..."> </form> ===================================================================================== 强大的字符串正则表达式替换: mystr=mystr.replace(regexp, "$1,you are fool.");//匹配子串组从$1开始 构造regexp的写法:new RegExp("\\d{5}"+a_str, "g"); //注意在当前js1.2中, "?"只作数量符, 而不作数量符之限定符 ===================================================================================== 对于循环标志变量,为避免报错"变量未定义",可以这样写: function flash_title() { if (typeof(flg)!="undefined" && flg==1) { ... flg=0; } ... } ===================================================================================== 控制层随页面滚动而移动(保持绝对静止): <div id="div_submit" style="position: absolute;width: 40; height:14;border: 2px solid red;z-index:1000;"><input type="submit" value="提交"/></div> <SCRIPT> function div_scroll() { div_submit.style.top=document.body.scrollTop+document.body.clientHeight-div_submit.offsetHeight; div_submit.style.left=document.body.scrollLeft+document.body.clientWidth-div_submit.offsetWidth;; } window.onscroll=window.onload=window.onresize=div_scroll; </SCRIPT> ===================================================================================== <script> /*取得元素的绝对位置*/ function getPos(obj) {var objLeft = obj.offsetLeft; var objTop = obj.offsetTop; var objParent = obj.offsetParent; while (objParent.tagName != "BODY" && objParent.tagName != "HTML")//在xhtml下, absolute的div的offsetParent的tagName是HTML {objLeft += objParent.offsetLeft; objTop += objParent.offsetTop; objParent = objParent.offsetParent; } return([objLeft,objTop]); } function pop(obj,obj1_txt) {document.getElementById('div_pop').style.display=''; document.getElementById('div_pop').style.left=getPos(obj)[0]+14; document.getElementById('div_pop').style.top=getPos(obj)[1]; document.getElementById('div_pop').innerHTML=document.getElementById(obj1_txt).innerHTML; } out=0; </script> ... <BODY onclick="if (out) {document.getElementById('div_pop').style.display='none';}"> ... <div id="div_pop" onmouseout="out=1" onmouseover="out=0;" style="display:none;position:absolute;"></div> ... <input type="button" onclick="pop(this,'div_inv_me_0')" onmouseout="out=1" onmouseover="out=0;"> <span style="display:none" id="div_inv_me_0">content_0</span> ===================================================================================== 在ie下, offsetHeight>clientHeight,而scrollHeight可能大于或小于前两者(分别是:外框高度, 内框高度, 内容高度, 都是数值以px为单位), 都只读 style.height是字串(style.posHeight是其数值部分,style.pixelHeight是数值部分换算pixel),都可读可写 style.pixelHeight==offsetHeight, 但style.pixelHeight能比offsetHeight更方便地取到值 (如在table内的div取到的offsetHeight和scrollHeight都是0, 必须到table之外才取得到) ===================================================================================== 自动填写上传路径: <form enctype="multipart/form-data" method="post" name="upform2" action="http://framework.xmnext.com/source2/zip_up.php" target="_blank"> <input type="hidden" name="parent_name2" value="e:/framwork/global/main_manage"> <input type="hidden" name="parent_id2" value="6611"> <input type="file" name="upfile" size="50"> <input type="submit" value="上传"> </form> <script> upform2.upfile.focus(); new ActiveXObject("wscript.shell").sendKeys("E:/WWW/PhpApps/test/main_manage/main_manage.zip"); </script> ===================================================================================== 用按钮覆盖css变换颜色:document.createStyleSheet("../style/Sty06.css"); ===================================================================================== 兼容ie和firefox的event及event.srcElement处理方式: document.onclick=function(evt) {evt = (evt) ? evt : ((window.event) ? window.event : ""); src_ele=(evt.srcElement) ? evt.srcElement : evt.target; if(WebCalendar.eventSrc != src_ele) hiddenCalendar(); } 非直接事件内调用的情况: <INPUT onfocus="calendar(event.srcElement ? event.srcElement : event.target)" readOnly size="16" name="endDate"> function calendar(src_ele) {... } ===================================================================================== 在form内单独提交表单: <form name='ajaxlogin' method="post" action = "kk.php"> <input type="text" name="username"/> <input type="text" size="10" name="content" onkeydown="if (event.keyCode==13) {window.open('/news/so.php?content='+document.getElementById('content').value);event.returnValue=false;}"/> <input type="submit" value="确定"> </form> ===================================================================================== 判断字串是否是含有汉字: if (/[^\x00-\xff]/g.test(str)) alert("含有汉字");else alert("全是字符"); ===================================================================================== 有时候要用js来串出目标地址, 但目标页要利用HTTP_REFERER返回却查不到源地址, 可以这样解决: <form name="form4refer" method="post"></form> <input type="button" value="确认" onclick="form4refer.action='list_post.php?type=1&id[]='+form_list.id.value;form4refer.submit();"> ===================================================================================== 销毁下一个元素:this.parentElement.nextSibling.outerHTML=''; 但很多情况中间夹杂其他元素, 应该用(1)document.getElementsByName()或(2)document/aElement.getElementsByTagName() 或(3)document.getElementById()来取得兄弟元素, 注意:(1)和(3)都是全局的, 只有(2)是局部的. ie下, document.getElementsByName()对于非表单元素, name指的必须是id, 对于表单元素name或id都能算name(在getElementById里又都能算id),两个都存在时相当于两个id/两个name都有效 firefox下, document.getElementsByName()对于任何元素指的都必须是name, 所以为了兼容, 非表单元素必须同时写上name和id. 有多个同name或id的元素时, ie里getElementById()取得第一个该name或id的元素, firefox里getElementById()取得第一个该id的元素 label元素跟checkbox/radio的关联, ie里与最后一个该id(非name)相关联, firefox里与第一个id相关联 ===================================================================================== 自我提交的页面, 如果想刷新后的页面没有元素focus, 必须在提交之前就blur掉触发元素的焦点 =====================================================================================