中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

21個(gè)值得收藏的Javascript技巧

2018-07-20    來(lái)源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

1  Javascript數(shù)組轉(zhuǎn)換為CSV格式

首先考慮如下的應(yīng)用場(chǎng)景,有一個(gè)Javscript的字符型(或者數(shù)值型)數(shù)組,現(xiàn)在需要轉(zhuǎn)換為以逗號(hào)分割的CSV格式文件。則我們可以使用如下的小技巧,代碼如下:


 
  1. var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; 
  2. var str = fruits.valueOf(); 


輸出:apple,peaches,oranges,mangoes

其中,valueOf()方法會(huì)將Javascript數(shù)組轉(zhuǎn)變?yōu)槎禾?hào)隔開的字符串。要注意的是,如果想不使用逗號(hào)分割,比如用|號(hào)分割,則請(qǐng)使用join方法,如下:


 
  1. var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; 
  2. var str = fruits.join("|"); 

輸出: apple|peaches|oranges|mangoes

2 將CSV格式重新轉(zhuǎn)換回Javscript數(shù)組

那么如何將一個(gè)CSV格式的字符串轉(zhuǎn)變回Javascript數(shù)組呢?可以使用split()方法,就可以使用任何指定的字符去分隔,代碼如下:


 
  1. var str = "apple, peaches, oranges, mangoes";  
  2. var fruitsArray = str.split(","); 


輸出 fruitsArray[0]: apple

3 根據(jù)索引移除數(shù)組中的某個(gè)元素

假如需要從Javascript數(shù)組中移除某個(gè)元素,可以使用splice方法,該方法將根據(jù)傳入?yún)?shù)n,移除數(shù)組中移除第n個(gè)元素(Javascript數(shù)組中從第0位開始計(jì)算)。


 
  1. function removeByIndex(arr, index) { 
  2.     arr.splice(index, 1); 
  3. test = new Array(); 
  4. test[0] = 'Apple'; 
  5. test[1] = 'Ball'; 
  6. test[2] = 'Cat'; 
  7. test[3] = 'Dog'; 
  8. alert("Array before removing elements: "+test); 
  9. removeByIndex(test, 2); 
  10. alert("Array after removing elements: "+test); 


則最后輸出的為Apple,Ball,Dog


4 根據(jù)元素的值移除數(shù)組元素中的值

下面這個(gè)技巧是很實(shí)用的,是根據(jù)給定的值去刪除數(shù)組中的元素,代碼如下:


 
  1. function removeByValue(arr, val) { 
  2.     for(var i=0; i<arr.length; i++) { 
  3.         if(arr[i] == val) { 
  4.             arr.splice(i, 1); 
  5.             break; 
  6.         } 
  7.     } 
  8.   
  9. var somearray = ["mon", "tue", "wed", "thur"] 
  10.   
  11. removeByValue(somearray, "tue"); 
  12.   
  13. //somearray 將會(huì)有的元素是 "mon", "wed", "thur" 


當(dāng)然,更好的方式是使用prototype的方法去實(shí)現(xiàn),如下代碼:


 
  1. Array.prototype.removeByValue = function(val) { 
  2.     for(var i=0; i<this.length; i++) { 
  3.         if(this[i] == val) { 
  4.             this.splice(i, 1); 
  5.             break; 
  6.         } 
  7.     } 
  8. //.. 
  9. var somearray = ["mon", "tue", "wed", "thur"] 
  10. somearray.removeByValue("tue"); 


5 通過(guò)字符串指定的方式動(dòng)態(tài)調(diào)用某個(gè)方法

有的時(shí)候,需要在運(yùn)行時(shí),動(dòng)態(tài)調(diào)用某個(gè)已經(jīng)存在的方法,并為其傳入?yún)?shù)。這個(gè)如何實(shí)現(xiàn)呢?下面的代碼可以:


 
  1. var strFun = "someFunction"; //someFunction 為已經(jīng)定義的方法名 
  2. var strParam = "this is the parameter"; //要傳入方法的參數(shù)   
  3. var fn = window[strFun]; 
  4.    
  5. //調(diào)用方法傳入?yún)?shù) 
  6. fn(strParam); 


6 產(chǎn)生1到N的隨機(jī)數(shù)


 
  1. var random = Math.floor(Math.random() * N + 1); 
  2.   
  3. //產(chǎn)生1到10之間的隨機(jī)數(shù) 
  4. var random = Math.floor(Math.random() * 10 + 1); 
  5.   
  6. //產(chǎn)生1到100之間的隨機(jī)數(shù) 
  7. var random = Math.floor(Math.random() * 100 + 1); 


7 捕捉瀏覽器關(guān)閉的事件

我們經(jīng)常希望在用戶關(guān)閉瀏覽器的時(shí)候,提示用戶要保存尚未保存的東西,則下面的這個(gè)Javascript技巧是十分有用的,代碼如下:


 
  1. <script language="javascript"> 
  2. function fnUnloadHandler() { 
  3.       
  4.        alert("Unload event.. Do something to invalidate users session.."); 
  5. </script> 
  6. <body onbeforeunload="fnUnloadHandler()"> 
  7. ………     
  8. </body> 


就是編寫onbeforeunload()事件的代碼即可


8  檢查是否按了回退鍵

同樣,可以檢查用戶是否按了回退鍵,代碼如下:


 
  1. window.onbeforeunload = function() {  
  2.     return "You work will be lost.";  
  3. }; 


9  檢查表單數(shù)據(jù)是否改變

有的時(shí)候,需要檢查用戶是否修改了一個(gè)表單中的內(nèi)容,則可以使用下面的技巧,其中如果修改了表單的內(nèi)容則返回true,沒(méi)修改表單的內(nèi)容則返回false。代碼如下:


 
  1. function formIsDirty(form) { 
  2.   for (var i = 0; i < form.elements.length; i++) { 
  3.     var element = form.elements[i]; 
  4.     var type = element.type; 
  5.     if (type == "checkbox" || type == "radio") { 
  6.       if (element.checked != element.defaultChecked) { 
  7.         return true; 
  8.       } 
  9.     } 
  10.     else if (type == "hidden" || type == "password" || 
  11.              type == "text" || type == "textarea") { 
  12.       if (element.value != element.defaultValue) { 
  13.         return true; 
  14.       } 
  15.     } 
  16.     else if (type == "select-one" || type == "select-multiple") { 
  17.       for (var j = 0; j < element.options.length; j++) { 
  18.         if (element.options[j].selected != 
  19.             element.options[j].defaultSelected) { 
  20.           return true; 
  21.         } 
  22.       } 
  23.     } 
  24.   } 
  25.   return false; 
  26. window.onbeforeunload = function(e) { 
  27.   e = e || window.event;   
  28.   if (formIsDirty(document.forms["someForm"])) { 
  29.     // IE 和 Firefox 
  30.     if (e) { 
  31.       e.returnValue = "You have unsaved changes."; 
  32.     } 
  33.     // Safari瀏覽器 
  34.     return "You have unsaved changes."; 
  35.   } 
  36. };

10  完全禁止使用后退鍵

下面的技巧放在頁(yè)面中,則可以防止用戶點(diǎn)后退鍵,這在一些情況下是需要的。代碼如下:


 
  1. <SCRIPT type="text/javascript"> 
  2.     window.history.forward(); 
  3.     function noBack() { window.history.forward(); } 
  4. </SCRIPT> 
  5. </HEAD> 
  6. <BODY onload="noBack();" 
  7.     onpageshow="if (event.persisted) noBack();" onunload=""> 


11 刪除用戶多選框中選擇的項(xiàng)目

下面提供的技巧,是當(dāng)用戶在下拉框多選項(xiàng)目的時(shí)候,當(dāng)點(diǎn)刪除的時(shí)候,可以一次刪除它們,代碼如下:


 
  1. function selectBoxRemove(sourceID) { 
  2.     //獲得listbox的id 
  3.     var src = document.getElementById(sourceID); 
  4.     //循環(huán)listbox 
  5.     for(var count= src.options.length-1; count >= 0; count--) { 
  6.          //如果找到要?jiǎng)h除的選項(xiàng),則刪除 
  7.         if(src.options[count].selected == true) { 
  8.                 try { 
  9.                          src.remove(count, null); 
  10.                            
  11.                  } catch(error) { 
  12.                            
  13.                          src.remove(count); 
  14.                 } 
  15.         } 
  16.     } 


12  Listbox中的全選和非全選

如果對(duì)于指定的listbox,下面的方法可以根據(jù)用戶的需要,傳入true或false,分別代表是全選listbox中的所有項(xiàng)目還是非全選所有項(xiàng)目,代碼如下:


 
  1. function listboxSelectDeselect(listID, isSelect) { 
  2.     var listbox = document.getElementById(listID); 
  3.     for(var count=0; count < listbox.options.length; count++) { 
  4.             listbox.options[count].selected = isSelect; 
  5.     } 



13 在Listbox中項(xiàng)目的上下移動(dòng)

下面的代碼,給出了在一個(gè)listbox中如何上下移動(dòng)項(xiàng)目


 
  1. unction listbox_move(listID, direction) { 
  2.    
  3.     var listbox = document.getElementById(listID); 
  4.     var selIndex = listbox.selectedIndex; 
  5.    
  6.     if(-1 == selIndex) { 
  7.         alert("Please select an option to move."); 
  8.         return; 
  9.     } 
  10.    
  11.     var increment = -1; 
  12.     if(direction == 'up') 
  13.         increment = -1; 
  14.     else 
  15.         increment = 1; 
  16.    
  17.     if((selIndex + increment) < 0 || 
  18.         (selIndex + increment) > (listbox.options.length-1)) { 
  19.         return; 
  20.     } 
  21.    
  22.     var selValue = listbox.options[selIndex].value; 
  23.     var selText = listbox.options[selIndex].text; 
  24.     listbox.options[selIndex].value = listbox.options[selIndex + increment].value 
  25.     listbox.options[selIndex].text = listbox.options[selIndex + increment].text 
  26.    
  27.     listbox.options[selIndex + increment].value = selValue; 
  28.     listbox.options[selIndex + increment].text = selText; 
  29.    
  30.     listbox.selectedIndex = selIndex + increment; 
  31. //.. 
  32. //.. 
  33.   
  34. listbox_move('countryList', 'up'); //move up the selected option 
  35. listbox_move('countryList', 'down'); //move down the selected option 


14 在兩個(gè)不同的Listbox中移動(dòng)項(xiàng)目

如果在兩個(gè)不同的Listbox中,經(jīng)常需要在左邊的一個(gè)Listbox中移動(dòng)項(xiàng)目到另外一個(gè)Listbox中去,下面是相關(guān)代碼:


 
  1. function listbox_moveacross(sourceID, destID) { 
  2.     var src = document.getElementById(sourceID); 
  3.     var dest = document.getElementById(destID); 
  4.    
  5.     for(var count=0; count < src.options.length; count++) { 
  6.    
  7.         if(src.options[count].selected == true) { 
  8.                 var option = src.options[count]; 
  9.    
  10.                 var newOption = document.createElement("option"); 
  11.                 newOption.value = option.value; 
  12.                 newOption.text = option.text; 
  13.                 newOption.selected = true; 
  14.                 try { 
  15.                          dest.add(newOption, null); //Standard 
  16.                          src.remove(count, null); 
  17.                  }catch(error) { 
  18.                          dest.add(newOption); // IE only 
  19.                          src.remove(count); 
  20.                  } 
  21.                 count--; 
  22.         } 
  23.     } 
  24. //.. 
  25. //.. 
  26.   
  27. listbox_moveacross('countryList', 'selectedCountryList'); 


15 快速初始化Javscript數(shù)組

下面的方法,給出了一種快速初始化Javscript數(shù)組的方法,代碼如下:


 
  1. var numbers = []; 
  2. for(var i=1; numbers.push(i++)<100;); 
  3. //numbers = [0,1,2,3 ... 100] 
  4. 使用的是數(shù)組的push方法 


16 截取指定位數(shù)的小數(shù)

如果要截取小數(shù)后的指定位數(shù),可以使用toFixed方法,比如:


 
  1. var num = 2.443242342; 
  2. alert(num.toFixed(2)); // 2.44 
  3. 而使用toPrecision(x)則提供指定位數(shù)的精度,這里的x是全部的位數(shù),如: 
  4. num = 500.2349; 
  5. result = num.toPrecision(4);//輸出500.2 


17 檢查字符串中是否包含其他字符串

下面的代碼中,可以實(shí)現(xiàn)檢查某個(gè)字符串中是否包含其他字符串。代碼如下:


 
  1. if (!Array.prototype.indexOf) {  
  2.     Array.prototype.indexOf = function(obj, start) { 
  3.          for (var i = (start || 0), j = this.length; i < j; i++) { 
  4.              if (this[i] === obj) { return i; } 
  5.          } 
  6.          return -1; 
  7.     } 
  8.   
  9. if (!String.prototype.contains) { 
  10.     String.prototype.contains = function (arg) { 
  11.         return !!~this.indexOf(arg); 
  12.     }; 


在上面的代碼中重寫了indexOf方法并定義了contains方法,使用的方法如下:


 
  1. var hay = "a quick brown fox jumps over lazy dog"; 
  2. var needle = "jumps"; 
  3. alert(hay.contains(needle)); 


18  去掉Javscript數(shù)組中的重復(fù)元素

下面的代碼可以去掉Javascript數(shù)組中的重復(fù)元素,如下:


 
  1. function removeDuplicates(arr) { 
  2.     var temp = {}; 
  3.     for (var i = 0; i < arr.length; i++) 
  4.         temp[arr[i]] = true; 
  5.   
  6.     var r = []; 
  7.     for (var k in temp) 
  8.         r.push(k); 
  9.     return r; 
  10.   
  11. //用法 
  12. var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange']; 
  13. var uniquefruits = removeDuplicates(fruits); 
  14. //輸出的 uniquefruits ['apple', 'orange', 'peach', 'strawberry']; 


19  去掉String中的多余空格

下面的代碼會(huì)為String增加一個(gè)trim()方法,代碼如下:


 
  1. if (!String.prototype.trim) { 
  2.    String.prototype.trim=function() { 
  3.     return this.replace(/^\s+|\s+$/g, ''); 
  4.    }; 
  5.   
  6. //用法 
  7. var str = "  some string    "; 
  8. str.trim(); 
  9. //輸出 str = "some string" 


20 Javascript中的重定向

在Javascript中,可以實(shí)現(xiàn)重定向,方法如下:


 
  1. window.location.href = "http://viralpatel.net"; 


21 對(duì)URL進(jìn)行編碼

有的時(shí)候,需要對(duì)URL中的傳遞的進(jìn)行編碼,方法如下:


 
  1. var myOtherUrl =  
  2.        "http://example.com/index.html?url=" + encodeURIComponent(myUrl); 

標(biāo)簽: 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:PHP生成圖形驗(yàn)證碼(大小寫字母與數(shù)字混合)

下一篇:php讀寫cookie的代碼