標籤:
具體如下:
//w作為window的形參,就表示window(function(w) {// 定義一個全域的window.wyl變數,就類似於jquery裡的$,Jquery對象w.wyl;/** * 模仿$(domObj)的形式,通過wyl(domObj)的方式把一個dom轉成wyl對象 * * @param para * @returns {wyl} 這裡的selector暫時只能是dom對象 */wyl = function(selector) {this._selector = selector;if (this == window) {// 我自己原來寫的// return this.wyl;return new wyl(selector);} else {// 用來儲存選中的元素this.elements = [];// 判斷selector的類型,因為jquery(xxx)中的xxx總共有三種類型,1 function ,2 字串 ,如// ‘#aa‘,‘.my‘等等 ; 3 dom對象也就是objectswitch (typeof selector) {case ‘function‘:this.wylAddEvent(w, ‘load‘, selector);break;// 類比 #xx選取器case ‘string‘:switch (selector.charAt(0)) {case ‘#‘:// 按照id選取器var obj = document.getElementById(selector.substring(1));this.elements.push(obj);break;case ‘.‘:// 按照class選取器this.elements = getEleByClas(document, selector.substring(1));break;default: // 按照tagNamethis.elements = document.getElementsByTagName(selector);}break;case ‘object‘:this.elements.push(selector);break;default:break;}// 根據name擷取dom/* var dom_ = document.getElementsByName(‘‘ + selector); *//** * 根據 document.getElementsByName(‘‘ +selector);的形式擷取到的dom對象 * 有length屬性,而通過getElementById擷取的dom對象沒有length屬性 * *//* * if (dom_.length) { alert(dom_.length); } else { * alert(dom_.innerHTML + ‘目前這個架構只能通過傳入name屬性來使用,無法通過id來解析dom對象‘); } */// 作用:返回當前對象,即返回window.wyl這個對象// return this;var this_ = [].push.apply(this, this.elements);// 注意這裡返回的不是this_而是thisreturn this;}}// 根據class進行選擇,即類比class選取器wyl.getEleByClas = function(oParent, sClass) {var aEle = document.getElementsByTagName("*");var aResults = [];for (i = 0; i < aEle.length; i++) {if (aEle[i].className == sClass) {aResults.push(aEle[i]);}}return aResults;}wyl.prototype.wylAddEvent = wyl.wylAddEvent = function(obj, sEv, fn) {if (obj.attachEvent) {obj.attachEvent(‘on‘ + sEv, fn);} else {obj.addEventListener(sEv, fn, false);}}// wyl.prototype.isArr的作用:在所有的wyl對象上加上isArr(para)的function,wyl.prototype.isArr = wyl.isArr = function(para) {/** * 在wyl對象上添加工具方法isArr(obj) 執行個體:var flag = wyl.isArr(obj); 如果為true那麼就說明是數組 */if (typeof para == ‘object‘ && para instanceof Array) {return true;} else {return false;}}/** * 實作類別似架構中的linkbutton()功能的方法 架構中的使用執行個體: $obj.linkbutton({ disabled:true }); * */wyl.prototype.print = wyl.print = function(para) {alert(para);return this;}wyl.prototype.linkbutton = wyl.linkbutton = function(para) {var _type = typeof para;if (_type != ‘object‘) {return this.print(‘傳入的參數必須是object‘);}// 存放傳入的obejct類型的參數var para_ = para || {};var f = para_.disabled;if (f == true) {$(this).removeClass();$(this).addClass(‘l-btn-disabled‘);return this;} else {$(this).removeClass();$(this).addClass(‘l-btn-abled‘);return this;}}// 傳入window對象})(window)
模仿jquery的一些實現 第二版