javascript 技巧總結積累109-173條(正在積累中)

來源:互聯網
上載者:User

109.改變狀態列 self.status ="";//

110.改變視窗大小 window.resizeTo(200,300);//

111.改變滑鼠樣式 style BODY{CURSOR: url('mouse.ani'); SCROLLBAR-BASE-COLOR: #506AA8; SCROLLBAR-ARROW-COLOR: #14213F; }//

112.背景透明 <input type="button" value="Button" style="background-color: transparent; border: 0;">//

113.滑鼠為等待形狀 <input type=button onclick="this.style.cursor='wait'">//

114.調用父視窗的函數 opener.fucntion1();//

115.body的內部html代碼 <input type="button" onclick="alert(code.document.body.innerHTML)" value="查看">//

116.架構中調用父視窗的函數 <INPUT TYPE='button' onclick='parent.test();' value='調用parent視窗的函數'>//

117.交換節點 <table  width=200  height=200  border> <tr><td  id=c1>CELL_1</td></tr> <tr><td  id=c2>CELL_2</td></tr> </table> <br> <input  type="button"  value="swap  row"  onclick="c1.swapNode(c2)">//

118.刪除節點 <table  width=200  height=200  border> <tr id=trall><td  id=c1>CELL_1</td></tr> <tr><td  id=c2>CELL_2</td></tr> </table> <br> <input  type="button"  value="swap  row"  onclick="trall.removeNode(c2)">//

119.添加節點 addNode()//

120.獲得事件的父與子標籤 event.srcElement.children[0]和event.srcElement.parentElement //

121.集中為按鈕改變顏色 <style> button{benc:expression(this.onfocus = function(){this.style.backgroundColor='#E5F0FF';})} </style> <button>New</button>//

122.判斷是左鍵還是右鍵被按下 <body onmousedown=if(event.button==1)alert("左鍵");if(event.button==2)alert("右鍵")>//

123.獲得作業系統的名稱和瀏覽器的名稱 document.write(navigator.userAgent)//

124.alt/ctrl/shift鍵按下 event.altKey //按下alt鍵 event.ctrlKey //按下ctrl鍵 event.shiftKey //按下shift鍵

 

125.將當前位置定位為C盤。 {window.location="c:"}//

126.返回輸入框的類型 <script> alert(event.srcElement.type);// </script>

127.類比控制項的單擊事件 <INPUT TYPE="hidden" name="guoguo" onclick="haha()"> <SCRIPT LANGUAGE="JavaScript"> <!--

function haha() { alert(); } guoguo.click(); //--> </SCRIPT>//

128.取出記錄集的列名 java.sql.ResultSet rset = com.bsitc.util.DBAssist.getIT().executeQuery(queryStatement, conn); java.sql.ResultSetMetaData metaData = rset.getMetaData(); int count = metaData.getColumnCount(); String name = metaData.getColumnName(i); String value = rset.getString(i);//

129.格式化數字 function format_number(str,digit) { if(isNaN(str)) {   alert("您傳入的值不是數字!");   return 0; } else if(Math.round(digit)!=digit) {   alert("您輸入的小數位元不是整數!");   return 0; } else   return Math.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit); }

130.斷行符號按鈕轉化為tab按鈕 if(event.keyCode==13) event.keyCode=9; //將

131.捲軸滾動 <button onclick="text1.scrollTop=text1.scrollHeight">Scroll</button><br> <textarea id="text1" cols=50 rows=10> 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 </textarea>//

132.判斷是什麼對象 if(typeof(unknown)=="function")return true; if(typeof(unknown)!="object")return false;//

133.取消文字框自動完成功能 <input type="text" autocomplete="off"> //

134.讓下拉框自動下拉 <select onmouseover="javascript:this.size=this.length" onmouseout="javascript:this.size=1"> <option value="">1</option> <option value="">2</option> <option value="">3</option> </select> //

135.讀取XML檔案 var childrenobj=myselect//document.all.myselect;     var oXMLDoc = new ActiveXObject('MSXML');     oXMLDoc.url = "mymsg.xml";     var oRoot=oXMLDoc.root;     if(oRoot.children != null) {         for(var i=0;i<oRoot.children.item(0).children.length;++i)   {             oItem = oRoot.children.item(0).children.item(i);             oOption = new Option(oItem.text,oItem.value);    childrenobj.add(oOption);         }     } //mymsg.xml檔案 <?xml version="1.0" encoding="gb2312" ?> <childrenlist> <aa> <child value='3301'>杭州地區</child>

<child value='3303'>溫州地區</child>

</aa> <aa> <child value='3310'>台州地區</child>

<child value='3311'>麗水地區</child> </aa> </childrenlist>//

136.點擊圖片,圖片停止 <a href="javascript:"><img src="http://www.51js.com/images/51js/red_forum.gif" border="0"></a>//

137.顯示本機電腦資訊 var WshNetwork = new ActiveXObject("WScript.Network"); alert("Domain = " + WshNetwork.UserDomain); alert("Computer Name = " + WshNetwork.ComputerName); alert("User Name = " + WshNetwork.UserName);//

138.比較時間   tDate = new Date(2004,01,08,14,35); //年,月,日,時,分   dDate = new Date();   tDate<dDate?alert("早於"):alert("晚於");//

139.彈出滑鼠所在處的鏈結地址   <body onmouseover="if (event.srcElement.tagName=='A')alert(event.srcElement.href)"><a

href="http://51js.com/viewthread.php?tid=13589" >dddd</a><input>//

140.注意不能通過與 undefined 做比較來測試一個變數是否存在,雖然可以檢查它的類型是否為“undefined”。在以

下的代碼範例中,假設程式員想測試是否已經聲明變數 x : // 這種方法不起作用 if (x == undefined)     // 作某些操作 // 這個方法同樣不起作用- 必須檢查

// 字串 "undefined" if (typeof(x) == undefined)     // 作某些操作 // 這個方法有效 if (typeof(x) == "undefined")     // 作某些操作

141.建立具有某些屬性的對象 var myObject = new Object(); myObject.name = "James"; myObject.age = "22"; myObject.phone = "555 1234";//

142.枚舉(迴圈)對象的所有屬性 for (var a in myObject) {     // 顯示 "The property 'name' is James",等等。     window.alert("The property '" + a + "' is " + myObject[a]); }//

143.判斷一個數字是否是整數 var a=23.2; alert(a%1==1)//

144.建立日期型變數 var a = new Date(2000, 1, 1); alert(a.toLocaleDateString());

145.給類定義新的方法 function trim_1() {   return this.replace(/(^/s*)|(/s*$)/g, ""); } String.prototype.trim=trim_1; alert('cindy'.trim());

146.定義一個將日期類型轉化為字串的方法 function guoguo_date() { var tmp1,tmp2; tmp1 =this.getMonth()+1+""; if(tmp1.length<2)   tmp1="0"+tmp1; tmp2 =this.getDate()+""; if(tmp2.length<2)   tmp2="0"+tmp2; return this.getYear()+"-"+tmp1+"-"+tmp2; } Date.prototype.toLiteString=guoguo_date; alert(new Date().toLiteString())

 

147. pasta 是有四個參數的構造器,定義對象。 function pasta(grain, width, shape, hasEgg) {     // 是用什麼糧食做的?     this.grain = grain;

    // 多寬?(數值)     this.width = width;    

    // 橫截面形狀?(字串)     this.shape = shape;  

    // 是否加蛋黃?(boolean)     this.hasEgg = hasEgg; 

    //定義方法     this.toString=aa; } function aa() { ; } //定義了物件建構器後,用 new 運算子建立對象執行個體。 var spaghetti = new pasta("wheat", 0.2, "circle", true); var linguine = new pasta("wheat", 0.3, "oval", true); //補充定義屬性,spaghetti和linguine都將自動獲得新的屬性 pasta.prototype.foodgroup = "carbohydrates";

148.列印出錯誤原因 try { x = y   // 產生錯誤。 } catch(e) {    document.write(e.description)   //列印 "'y' is undefined". }//

149.產生EXCEL檔案並儲存 var ExcelSheet; ExcelApp = new ActiveXObject("Excel.Application"); ExcelSheet = new ActiveXObject("Excel.Sheet"); //本代碼啟動建立對象的應用程式(在這種情況下,Microsoft Excel 工作表)。一旦對象被建立,就可以用定義的對

象變數在代碼中引用它。 在下面的例子中,通過物件變數 ExcelSheet 訪問新對象的屬性和方法和其他 Excel 對象,

包括 Application 對象和 ActiveSheet.Cells 集合。 // 使 Excel 通過 Application 對象可見。 ExcelSheet.Application.Visible = true; // 將一些文本放置到表格的第一格中。 ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"; // 儲存表格。 ExcelSheet.SaveAs("C://TEST.XLS"); // 用 Application 對象用 Quit 方法關閉 Excel。 ExcelSheet.Application.Quit();//

150.根據標籤獲得一組對象 var coll = document.all.tags("DIV"); if (coll!=null) { for (i=0; i<coll.length; i++) ... }//     151.實現預覽列印及列印 <OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height=0 id=wb name=wb width=0></OBJECT> <input type=button value=預覽列印 onclick="wb.execwb(7,1)"> <input type=button onClick=document.all.wb.ExecWB(6,1) value="列印">//

152.不通過form,直接通過名字引用對象 <INPUT TYPE="text" NAME="gg" value=aaaaa> <SCRIPT LANGUAGE="JavaScript"> <!-- alert(document.all.gg.value) //--> </SCRIPT>//

153.使滑鼠滾輪失效 function document.onmousewheel() { return false; }// 154.建立快顯視窗 <SCRIPT LANGUAGE="JScript">   var oPopup = window.createPopup();   var oPopupBody = oPopup.document.body;   oPopupBody.innerHTML = "Display some <B>HTML</B> here.";   oPopup.show(100, 100, 200, 50, document.body); </SCRIPT>//

155.取得滑鼠所在處的對象 var obj = document.elementFromPoint(event.x,event.y);//

156.獲得左邊的對象 <INPUT TYPE="text" NAME="gg"><INPUT TYPE="text" NAME="bb"

onclick="this.previousSibling.value='guoguo'">//

157.定位滑鼠 document.all.hint_layer.style.left  = event.x+document.body.scrollLeft+10; document.all.hint_layer.style.top  = event.y+document.body.scrollTop+10;//

158.向下拉框指定位置添加項目 var op  = document.createElement("OPTION"); document.all.selected_items.children(index).insertAdjacentElement("BeforeBegin",op); op.text  = document.all.all_items[i].text; op.value = document.all.all_items[i].value;//

159.判斷一個視窗是否已經開啟,如果已經開啟,則關閉之 var a; if(a) a.close(); else a=window.open('','','');//

160.動態建立一個標籤 newElem  = document.createElement("DIV"); newElem.id = "hint_layer"; document.body.appendChild(newElem); document.all.hint_layer.innerText="guoguo";//

161.標題列 document.title//

162.背景圖片 <body style="BACKGROUND-ATTACHMENT: fixed" background="img/bgfix.gif" ></body>//背景圖片不動

<STYLE TYPE="text/css"> <!-- BODY {background-image:img/bgchild.jpg; background-position: center; background-repeat: no-repeat; background-attachment: fixed;} --> </STYLE>//背景圖片置中

163.設定透明效果 document.form.xxx.filters.alpha.opacity=0~100//

164.定義方法 var dragapproved=false; document.onmouseup=new Function("dragapproved = false");// 165.將數字轉化為人民幣大寫形式 function convertCurrency(currencyDigits) { // Constants: var MAXIMUM_NUMBER = 99999999999.99; // Predefine the radix characters and currency symbols for output: var CN_ZERO = "零"; var CN_ONE = "壹"; var CN_TWO = "貳"; var CN_THREE = "三"; var CN_FOUR = "肆"; var CN_FIVE = "伍"; var CN_SIX = "陸"; var CN_SEVEN = "柒"; var CN_EIGHT = "捌"; var CN_NINE = "玖"; var CN_TEN = "拾"; var CN_HUNDRED = "佰"; var CN_THOUSAND = "仟"; var CN_TEN_THOUSAND = "萬"; var CN_HUNDRED_MILLION = "億"; var CN_SYMBOL = "人民幣"; var CN_DOLLAR = "元"; var CN_TEN_CENT = "角"; var CN_CENT = "分"; var CN_INTEGER = "整"; // Variables: var integral; // Represent integral part of digit number. var decimal; // Represent decimal part of digit number. var outputCharacters; // The output result. var parts; var digits, radices, bigRadices, decimals; var zeroCount; var i, p, d; var quotient, modulus; // Validate input string: currencyDigits = currencyDigits.toString(); if (currencyDigits == "") {   alert("Empty input!");   return ""; } if (currencyDigits.match(/[^,./d]/) != null) {   alert("Invalid characters in the input string!");   return ""; } if ((currencyDigits).match(/^((/d{1,3}(,/d{3})*(.((/d{3},)*/d{1,3}))?)|(/d+(./d+)?))$/) == null) {   alert("Illegal format of digit number!");   return ""; } // Normalize the format of input digits: currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters. currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning. // Assert the number is not greater than the maximum number. if (Number(currencyDigits) > MAXIMUM_NUMBER) {   alert("Too large a number to convert!");   return ""; } // Process the coversion from currency digits to characters: // Separate integral and decimal parts before processing coversion: parts = currencyDigits.split("."); if (parts.length > 1) {   integral = parts[0];   decimal = parts[1];   // Cut down redundant decimal digits that are after the second.   decimal = decimal.substr(0, 2); } else {   integral = parts[0];   decimal = ""; } // Prepare the characters corresponding to the digits: digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT,

CN_NINE); radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND); bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION); decimals = new Array(CN_TEN_CENT, CN_CENT); // Start processing: outputCharacters = ""; // Process integral part if it is larger than 0: if (Number(integral) > 0) {   zeroCount = 0;   for (i = 0; i < integral.length; i++) {    p = integral.length - i - 1;    d = integral.substr(i, 1);    quotient = p / 4;    modulus = p % 4;    if (d == "0") {     zeroCount++;    }    else {     if (zeroCount > 0)     {      outputCharacters += digits[0];     }     zeroCount = 0;     outputCharacters += digits[Number(d)] + radices[modulus];    }    if (modulus == 0 && zeroCount < 4) {     outputCharacters += bigRadices[quotient];    }   }   outputCharacters += CN_DOLLAR; } // Process decimal part if there is: if (decimal != "") {   for (i = 0; i < decimal.length; i++) {    d = decimal.substr(i, 1);    if (d != "0") {     outputCharacters += digits[Number(d)] + decimals[i];    }   } } // Confirm and return the final output string: if (outputCharacters == "") {   outputCharacters = CN_ZERO + CN_DOLLAR; } if (decimal == "") {   outputCharacters += CN_INTEGER; } outputCharacters = CN_SYMBOL + outputCharacters; return outputCharacters; }//

166.xml資料島綁定表格 <html> <body> <xml id="abc" src="test.xml"></xml> <table border='1' datasrc='#abc'> <thead> <td>接收人</td> <td>發送人</td> <td>主題</td> <td>內容</td> </thead> <tfoot> <tr><th>表格的結束</th></tr> </tfoot> <tr> <td><div datafld="to"></div></td> <td><div datafld="from"></div></td> <td><div datafld="subject"></div></td> <td><div datafld="content"></div></td> </tr> </table> </body> </html>

//cd_catalog.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!--  Edited with XML Spy v4.2   --> <CATALOG> <CD>   <TITLE>Empire Burlesque</TITLE>   <ARTIST>Bob Dylan</ARTIST>   <COUNTRY>USA</COUNTRY>   <COMPANY>Columbia</COMPANY>   <PRICE>10.90</PRICE>   <YEAR>1985</YEAR>   </CD> <CD>   <TITLE>Hide your heart</TITLE>   <ARTIST>Bonnie Tyler</ARTIST>   <COUNTRY>UK</COUNTRY>   <COMPANY>CBS Records</COMPANY>   <PRICE>9.90</PRICE>   <YEAR>1988</YEAR>   </CD> <CD>   <TITLE>Greatest Hits</TITLE>   <ARTIST>Dolly Parton</ARTIST>   <COUNTRY>USA</COUNTRY>   <COMPANY>RCA</COMPANY>   <PRICE>9.90</PRICE>   <YEAR>1982</YEAR>   </CD> <CD>   <TITLE>Still got the blues</TITLE>   <ARTIST>Gary Moore</ARTIST>   <COUNTRY>UK</COUNTRY>   <COMPANY>Virgin records</COMPANY>   <PRICE>10.20</PRICE>   <YEAR>1990</YEAR>   </CD> </CATALOG> //

167.以下組合可以正確顯示漢字 ================================ xml儲存編碼 xml頁面指定編碼 ANSI  gbk/GBK、gb2312 Unicode  unicode/Unicode UTF-8  UTF-8 ================================

168.XML操作 <xml id="xmldata" src="/data/books.xml"> <div id="guoguo"></div> <script> var x=xmldata.recordset //取得資料島中的記錄集 if(x.absoluteposition < x.recordcount) //如果當前的絕對位置在最後一條記錄之前 { x.movenext();     //向後移動 x.moveprevious();    //向前移動 x.absoluteposition=1;   //移動到第一條記錄 x.absoluteposition=x.recordcount;//移動到最後一條記錄,注意記錄集x.absoluteposition是從1到記錄集記錄的個

數的 guoguo.innerText=xmldso.recordset("field_name"); //從中取出某條記錄 } </script>

169.動態修改CSS的另一種方式 this.runtimeStyle.cssText = "color:#990000;border:1px solid #cccccc";//

170.Regex 匹配中文字元的Regex: [/u4e00-/u9fa5]

匹配雙位元組字元(包括漢字在內):[^/x00-/xff]

應用:計算字串的長度(一個雙位元組字元長度計2,ASCII字元計1)

String.prototype.len=function(){return this.replace([^/x00-/xff]/g,"aa").length;}

匹配空行的Regex:/n[/s| ]*/r

匹配HTML標記的Regex:/<(.*)>.*<///1>|<(.*) //>/

匹配首尾空格的Regex:(^/s*)|(/s*$)

應用:javascript中沒有像vbscript那樣的trim函數,我們就可以利用這個運算式來實現,如下:

String.prototype.trim = function() {     return this.replace(/(^/s*)|(/s*$)/g, ""); }

////////利用Regex分解和轉換IP地址:

下面是利用Regex匹配IP地址,並將IP地址轉換成對應數值的Javascript程式:

function IP2V(ip) { re=/(/d+)/.(/d+)/.(/d+)/.(/d+)/g  //匹配IP地址的Regex if(re.test(ip)) { return RegExp.$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!") } }

不過上面的程式如果不用Regex,而直接用split函數來分解可能更簡單,程式如下:

var ip="10.100.20.168" ip=ip.split(".") alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))

匹配Email地址的Regex:/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*

匹配網址URL的Regex:http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?

//////////利用Regex去除字串中重複的字元的演算法程式:

var s="abacabefgeeii" var s1=s.replace(/(.).*/1/g,"$1") var re=new RegExp("["+s1+"]","g") var s2=s.replace(re,"") alert(s1+s2)  //結果為:abcefgi

思路是使用後向引用取出包括重複的字元,再以重複的字元建立第二個運算式,取到不重複的字元,兩者串聯。這個方

法對於字元順序有要求的字串可能不適用。

//////////得用Regex從URL地址中提取檔案名稱的javascript程式,如下結果為page1

s="http://www.9499.net/page1.htm" s=s.replace(/(.*//){0,}([^/.]+).*/ig,"$2") alert(s)

/////////利用Regex限制網頁表單裡的文字框輸入內容:

用Regex限制只能輸入中文:onkeyup="value=value.replace(/[^/u4E00-/u9FA5]/g,'')"

onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,'')

)"

用Regex限制只能輸入全形字元: onkeyup="value=value.replace(/[^/uFF00-/uFFFF]/g,'')"

onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/uFF00-/uFFFF]/g,'')

)"

用Regex限制只能輸入數字:onkeyup="value=value.replace(/[^/d]/g,'')

"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"

用Regex限制只能輸入數字和英文:onkeyup="value=value.replace(/[/W]/g,'')

"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"

171.設定和使用cookie <HTML> <BODY> 設定與讀取 cookies...<BR> 寫入cookie的值<input type=text name=gg> <INPUT TYPE = BUTTON Value = "設定cookie" onClick = "Set()"> <INPUT TYPE = BUTTON Value = "讀取cookie" onClick = "Get()"><BR> <INPUT TYPE = TEXT NAME = Textbox> </BODY> <SCRIPT LANGUAGE="JavaScript"> function Set() { var Then = new Date() Then.setTime(Then.getTime() + 60*1000 ) //60秒 document.cookie = "Cookie1="+gg.value+";expires="+ Then.toGMTString() }

function Get() { var cookieString = new String(document.cookie) var cookieHeader = "Cookie1=" var beginPosition = cookieString.indexOf(cookieHeader) if (beginPosition != -1) {   document.all.Textbox.value = cookieString.substring(beginPosition  + cookieHeader.length) } else   document.all.Textbox.value = "Cookie 未找到!" } </SCRIPT> </HTML>//

172.取月的最後一天 function getLastDay(year,month) { //取年 var new_year = year; //取到下一個月的第一天,注意這裡傳入的month是從1~12 var new_month = month++; //如果當前是12月,則轉至下一年 if(month>12) {   new_month -=12;   new_year++; } var new_date = new Date(new_year,new_month,1); return (new Date(new_date.getTime()-1000*60*60*24)).getDate(); }//

173.判斷當前的焦點是組中的哪一個 for(var i=0;i<3;i++) if(event.srcElement==bb[i])   break;//

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.