我自己的Javascript 库,封装了一些常用函数
现在Javascript库海量,流行的也多,比如jQuery,YUI等,虽然功能强大,但也是不万能的,功能不可能涉及方方面面,自己写一个的JS库是对这些的补充,很多也比较实用,把应用到项目中中去也比较方面,这也是对工作的一些积累,也加深对知识的理解。
2012-6-20更新,添加设置Cookie,获取Cookie,删除Cookie方法。很实用哦.......................
2012-7-22更新,表格排序,获取URL参数,批量清除Cookie...
2012-8-24更新,动态加载JS,Ajax封装,HTML编码...
1 /** 2 @ Name : Kingwell Javascript Library 3 @ Author :kingwell 4 @ Date : 2012-8-22 5 @ Email : jinhua.leng##gmail.com 6 @ Version : 1.2 7 @ Update : http://kingwell-leng.iteye.com/blog/1570768 8 功能: 9 1: $ID选择 10 2: 事件绑定,事件移除,获取事件目标 11 3: 阻止冒泡,阻止默认事件 12 4: 显示隐藏 13 5: 去除HTML 14 6: 去除首尾空格 15 7: 获取URL参数 16 8: Cookie操作,设置,删除,获取 17 9: 清除所有Cookie 18 10:表格排序 19 11: 动态转入Javascript 20 12: 封装Ajax 21 13:将HTML编码 22 调用方法: 23 KW.x(); 24 */ 25 (function () { 26 if (!window.KW) { 27 window.KW = {}; 28 }; 29 window.KW = { 30 version : "1.2", 31 $ : function () { //$()函数 32 var elements = new Array(); 33 for (var i = 0; i <= arguments.length; i++) { 34 var element = arguments[i]; 35 //如果是一个字符串那假设它是一个ID 36 if (typeof element == 'string') { 37 element = document.getElementById(element); 38 } 39 //如果只提供了一个参数,则立即返回这个参数 40 if (arguments.length == 1) { 41 return element; 42 } 43 //否则,将它添加到数组中 44 elements.push(element); 45 } 46 return elements; 47 }, 48 /*-------------------- 事件处理 --------------------*/ 49 addEvent : function (oTarget, oType, fnHandler) { //-----添加事件; 50 var oT = typeof oTarget == "string" ? this.$(oTarget) : oTarget; 51 if (!oT) { 52 alert('Not found \" ' + oTarget + ' \"'); 53 return false 54 }; 55 if (oT.addEventListener) { //for DOM 56 oT.addEventListener(oType, fnHandler, false); 57 } else if (oT.attachEvent) { //for IE 58 oT.attachEvent('on' + oType, fnHandler); 59 } else { //for Others 60 oT['on' + oType] = fnHandler; 61 } 62 }, 63 removeEvent : function (oTarget, oType, fnHandler) { //-----移除事件; 64 var oT = this.$(oTarget); 65 if (!oT) { 66 alert('Not found \" ' + oTarget + ' \"'); 67 return false 68 }; 69 if (oT.removeEventListener) { //for DOM 70 oT.removeEventListener(oType, fnHandler, false); 71 } else if (oT.detachEvent) { //for IE 72 oT.detachEvent('on' + oType, fnHandler); 73 } else { //for Others 74 oT['on' + oType] = null; 75 } 76 }, 77 getEvent : function (ev) { //-----获得事件----- 78 return ev || window.event; 79 }, 80 getTarget : function (ev) { //-----获取目标---- 81 return this.getEvent(ev).target || this.getEvent().srcElement; 82 }, 83 stopPropagation : function () { //-----阻止冒泡----- 84 if (window.event) { 85 return this.getEvent().cancelBubble = true; 86 } else { 87 return arguments.callee.caller.arguments[0].stopPropagation(); 88 } 89 }, 90 stopDefault : function () { //-----阻止默认行为 91 if (window.event) { 92 return this.getEvent().returnValue = false; 93 } else { 94 return arguments.callee.caller.arguments[0].preventDefault(); 95 } 96 }, 97 /*-------------------- 常用函数 --------------------*/ 98 toggleDisplay : function (id) { //-----显示,隐藏----- 99 var oTarget = this.$(id); 100 if (!oTarget) { 101 return false; 102 } 103 oTarget.style.display == 'none' ? oTarget.style.display = 'block' : oTarget.style.display = 'none'; 104 }, 105 stripHTML : function (agr) { //-----移除HTML----- 106 var reTag = /<(?:.|\s)*?>/g; 107 return agr.replace(reTag, '') 108 }, 109 stripSpace : function (oTarget) { //-----移除空格----- 110 var re = /^\s*(.*?)\s*$/; 111 return oTarget.replace(re, '$1'); 112 }, 113 isEmail : function (e) { //-----Is E-mail 114 var re = /^[a-zA-z_][a-zA-Z_0-9]*?@\w{1,}.\[a-zA-Z]{1,}/; 115 return re.test(e); 116 }, 117 /*-------------------- Cookie操作 --------------------*/ 118 setCookie : function (sName, sValue, oExpires, sPath, sDomain, bSecure) { //-----设置Cookie----- 119 var sCookie = sName + '=' + encodeURIComponent(sValue); 120 if (oExpires) { 121 var date = new Date(); 122 date.setTime(date.getTime() + oExpires * 60 * 60 * 1000); 123 sCookie += '; expires=' + date.toUTCString(); 124 } 125 if (sPath) { 126 sCookie += '; path=' + sPath; 127 } 128 if (sDomain) { 129 sCookie += '; domain=' + sDomain; 130 } 131 if (bSecure) { 132 sCookie += '; secure'; 133 } 134 document.cookie = sCookie; 135 }, 136 getCookie : function (sName) { //-----获得Cookie值----- 137 var sRE = '(?:; )?' + sName + '=([^;]*)'; 138 var oRE = new RegExp(sRE); 139 if (oRE.test(document.cookie)) { 140 return decodeURIComponent(RegExp['$1']); 141 } else { 142 return null; 143 } 144 }, 145 deleteCookie : function (sName, sPath, sDomain) { //-----删除Cookie值----- 146 this.setCookie(sName, '', new Date(0), sPath, sDomain); 147 }, 148 clearCookie : function () { //清除所有Cookie 149 var cookies = document.cookie.split(";"); 150 var len = cookies.length; 151 for (var i = 0; i < len; i++) { 152 var cookie = cookies[i]; 153 var eqPos = cookie.indexOf("="); 154 var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; 155 name = name.replace(/^\s*|\s*$/, ""); 156 document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/" 157 } 158 }, 159 convert : function (sValue, sDataType) { //类型转,根据不同类型数据排序,比如,整型,日期,浮点,字符串,接受两个参数,一个是值,一个是排序的数据类型 160 switch (sDataType) { 161 case "int": 162 return parseInt(sValue); 163 case "float": 164 return parseFloat(sValue); 165 case "date": 166 return new Date(Date.parse(sValue)); 167 default: 168 return sValue.toString(); 169 } 170 }, 171 geterateCompareTRs : function (iCol, sDataType) { //比较函数,用于sort排序用 172 return function compareTRs(oTR1, oTR2) { 173 var vValue1, 174 vValue2; 175 if (oTR1.cells[iCol].getAttribute("value")) { //用于高级排序,比如图片,添加一个额外的属性来排序 176 vValue1 = KW.convert(oTR1.cells[iCol].getAttribute("value"), sDataType); 177 vValue2 = KW.convert(oTR2.cells[iCol].getAttribute("value"), sDataType); 178 } else { 179 vValue1 = KW.convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType); 180 vValue2 = KW.convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType); 181 } 182 if (vValue1 < vValue2) { 183 return -1; 184 } else if (vValue1 > vValue2) { 185 return 1; 186 } else { 187 return 0; 188 } 189 } 190 }, 191 tabSort : function (sTableID, iCol, sDataType) { //排序函数,sTableID为目标,iCol哪列排序,为必需,sDataType可选 192 var oTable = document.getElementById(sTableID); 193 var oTBody = oTable.tBodies[0]; 194 var colDataRows = oTBody.rows; 195 var aTRs = []; 196 var len = colDataRows.length; 197 for (var i = 0; i < len; i++) { 198 aTRs[i] = colDataRows[i]; 199 }; 200 if (oTable.sortCol == iCol) { //如果已经排序,则倒序 201 aTRs.reverse(); 202 } else { 203 aTRs.sort(this.geterateCompareTRs(iCol, sDataType)); 204 } 205 var oFragment = document.createDocumentFragment(); 206 var trlen = aTRs.length; 207 for (var j = 0; j < trlen; j++) { 208 oFragment.appendChild(aTRs[j]); 209 }; 210 oTBody.appendChild(oFragment); 211 oTable.sortCol = iCol; //设置一个状态 212 }, 213 GetQueryString : function (name) { 214 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 215 var r = window.location.search.substr(1).match(reg); 216 if (r != null) 217 return unescape(r[2]); 218 return null; 219 }, 220 HTMLEscape : function (str) { 221 var s = ""; 222 if (str.length == 0) { 223 return ""; 224 } 225 s = str.replace(/&/g, "&"); 226 s = s.replace(/</g, "<"); 227 s = s.replace(/>/g, ">"); 228 s = s.replace(/ /g, " "); 229 s = s.replace(/\'/g, "'"); 230 s = s.replace(/\"/g, """); 231 return s; 232 }, 233 loadJS : function (url) { 234 var statu = true; //初始状态 235 var js = document.getElementsByTagName("script"); 236 var len = js.length; 237 for (var i = 0; i < len; i++) { 238 if (js[i].getAttribute("src") == url) { 239 statu = false; //如果已经添加,则设置为Flase,不再添加 240 } 241 } 242 if (statu) { 243 var script = document.createElement("script"); 244 script.type = "text/javascript"; 245 script.src = url; 246 var header = document.getElementsByTagName("head")[0]; 247 header.appendChild(script); 248 249 } 250 }, 251 ajax : function (obj) { 252 if (!obj.url) { 253 return false; 254 }; 255 var method = obj.type || "GET"; 256 var async = obj.async || true; 257 var dataType = obj.dataType; 258 var XHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 259 XHR.open(method, obj.url, async); 260 XHR.setRequestHeader('If-Modified-Since', 'Thu, 06 Apr 2006 00:00: 00 GMT'); 261 XHR.send(null); 262 if (obj.sendBefore) { 263 obj.sendBefore(); 264 }; 265 XHR.onreadystatechange = function () { 266 if (XHR.readyState == 4 && (XHR.status >= 200 && XHR.status < 300 || XHR.status == 304)) { 267 268 if (obj.success) { 269 if (dataType && dataType.toLocaleLowerCase() === "json") { 270 obj.success(eval("(" + XHR.responseText + ")")) 271 } else if (dataType && dataType.toLocaleLowerCase() === "xml") { 272 obj.success(XHR.responseXML) 273 } else { 274 obj.success(XHR.responseText); 275 } 276 }; 277 if (obj.complete) { 278 obj.complete() 279 } 280 281 } else { 282 if (obj.complete) { 283 obj.complete() 284 } 285 if (obj.error) { 286 obj.error("The XMLHttpRequest failed. status: " + XHR.status); 287 } 288 289 } 290 291 } 292 } 293 294 }; 295 296 })();
不断地完善中....