標籤:
按鈕樣式定義<style>.btn{display: inline-block;width: 100px;height: 20px;color: #fff;font-size: 12px;background-color: #0033dd;text-align: center;line-height: 20px;text-decoration: none;border: 5px #0000ff outset;}.btn-big-test{width: 300px;height: 85px;line-height: 85px;font-size: 25px;}</style>
用基礎js 實現了一個簡單的具有元素選擇支按id/name/class /tag/對象等方式的基礎選取器,並實現了事件委託和移除機制,實現了屬性操作功能和連續調用模式.異常捕捉
聲明按鈕<a href="javascript:;" class="btn-big-test btn" title=‘你點了一個巨大的按鈕!‘>巨大的測試按鈕</a><br/><br/><a href="javascript:;" id="removetest" class="btn grey">移除test事件</a> <a href="javascript:;" id="addtest" class="btn">開啟test事件</a>
/*聲明函數*/$_fn=function(selectName){this.selectName=selectName;this.obj=this.selectElement();return this;}//原型方法$_fn.prototype={//基礎選取器 不包含子類 連續等模式選取器‘selectElement‘:function(){if(typeof this.selectName == ‘object‘){return this.selectName;}else if(this.selectName.indexOf("#")!=-1){return document.getElementById(this.selectName.replace(‘#‘,‘‘));}else if(this.selectName.indexOf(".")!=-1){return document.getElementsByClassName(this.selectName.replace(‘.‘,‘‘));}else if(this.selectName.indexOf("@")!=-1){return document.getElementsByName(this.selectName.replace(‘@‘,‘‘));}else{return document.getElementsByTagName(this.selectName);}},‘on‘:function(event,callback){try{$_eventStack[this.obj]=callback;if (/.*(Firefox|Safari|Chrome).*/.exec(window.navigator.userAgent)) {if(this.obj.length>0){for (var i=0;i<this.obj.length;i++) {this.obj[i].addEventListener("click",callback,false);};}else{this.obj.addEventListener("click",callback,false);}}else{if(this.obj.length>0){for (var i=0;i<this.obj.length;i++) {if(this.obj[i])this.obj[i].attachEvent=("onclick",callback);}}else{this.obj.attachEvent=("onclick",callback);}}}catch(e){console.error(e);}return this;},detach:function(event){try{if (/.*(Firefox|Safari|Chrome).*/.exec(window.navigator.userAgent)) {if(this.obj.length>0){for (var i=0;i<this.obj.length;i++) {this.obj[i].removeEventListener(event,$_eventStack[this.obj],false);};}else{this.obj.removeEventListener(event,$_eventStack[this.obj],false);}}else{if(this.obj.length>0){for (var i=0;i<this.obj.length;i++) {if(this.obj[i])this.obj[i].detachEvent("on"+event,$_eventStack[this.obj]);}}else{this.obj.detachEvent("on"+event,$_eventStack[this.obj]);}}}catch(e){console.error(e);}return this;},attr:function(propName,value){if(!value){return this.obj.getAttribute(propName);}else{this.obj.setAttribute(value);return this;}}} window.$_ = function(selectName){return new $_fn(selectName);};//擷取智能對象 window.$_eventStack={};//記錄事件委託關係
///////////////////////////////
設定按鈕事件
$_(".btn-big-test").on(‘click‘,function(e){ alert($_(this).attr("title")); });
$_("#removetest").on("click",function(){ $_(".btn-big-test").detach(‘click‘); alert("事件已移除"); });
$_("#addtest").on("click",function(){ //採用連續調用模式銷毀事件和委託新的事件 避免多次調用 $_(".btn-big-test").detach(‘click‘).on(‘click‘,function(e){ alert(this.className); }); alert("事件已添加"); });
js實作類別似jquery基礎功能 簡單選取器/事件/屬性