按钮样式定义
<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("事件已添加");
});