本系列文章旨在記錄一些實用的javascript技巧,既可以作為一個知識的積累,又可以作為閑暇時打發(fā)時間寫寫代碼的記錄。同時也方便日后翻閱~
1 2 3 |
var myString = "hello all"; var code = encodeURI(myString); //結(jié)果: "hello%20all" var str = decodeURI(code); //結(jié)果: "hello all" |
相應(yīng)的還有: encodeURIComponent() decodeURIComponent()
1 2 3 |
var myString = "hello"; var code = myString.charCodeAt(3); //返回"l"的Unicode編碼(整型) var char = String.fromCharCode(66); //返回Unicode為66的字符 |
1 2 3 4 5 6 7 |
function focusLast(){ var e = event.srcElement; var r =e.createTextRange(); r.moveStart('character',e.value.length); r.collapse(true); r.select(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function getUrlState(URL){ var xmlhttp = new ActiveXObject("microsoft.xmlhttp"); xmlhttp.Open("GET",URL, false); try{ xmlhttp.Send(); }catch(e){ }finally{ var result = xmlhttp.responseText; if(result){ if(xmlhttp.Status==200){ return(true); }else{ return(false); } }else{ return(false); } } } |
1 2 3 4 5 6 7 8 9 |
function formatCss(s){//格式化代碼 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); s = s.replace(/;\s*;/g, ";"); //清除連續(xù)分號 s = s.replace(/\,[\s\.\#\d]*{/g, "{"); s = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2"); s = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2"); s = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2"); return s; } |
1 2 3 4 5 6 7 8 |
function yasuoCss (s) {//壓縮代碼 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //刪除注釋 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容錯處理 s = s.replace(/;\s*;/g, ";"); //清除連續(xù)分號 s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白 return (s == null) ? "" : s[1]; } |
1 2 3 4 5 6 7 |
var currentPageUrl = ""; if (typeof this.href === "undefined") { currentPageUrl = document.location.toString().toLowerCase(); } else { currentPageUrl = this.href.toString().toLowerCase(); } |
1 2 3 4 5 6 7 |
function _ip2int(ip){ var num = 0; ip = ip.split("."); num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]); num = num >>> 0; return num; } |
1 2 3 4 5 6 7 8 9 10 |
function _int2iP(num){ var str; var tt = new Array(); tt[0] = (num >>> 24) >>> 0; tt[1] = ((num << 8) >>> 24) >>> 0; tt[2] = (num << 16) >>> 24; tt[3] = (num << 24) >>> 24; str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]); return str; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function checkAll() { var selectall = document.getElementById("selectall"); var allbox = document.getElementsByName("allbox"); if (selectall.checked) { for (var i = 0; i < allbox.length; i++) { allbox[i].checked = true; } } else { for (var i = 0; i < allbox.length; i++) { allbox[i].checked = false; } } } |
查看更多本系列文章:JS手記
更多建議: