JavaScript中绑定事件的三种方式及去除绑定
在JavaScript中,有三种常用的绑定事件的方法
第一种办法
函数写在结构层里面
非常不好,使页面很混乱,行为与结构得不到分离
<inputtype="button"onclick="func();">
绑定事件的第二种办法
好处:行为与结构开始分离
缺点:
第二种绑定方式中只能给一个时间绑定一个处理函数
即.onclick=fn1; . onclick=fn2最终的效果是onclick=fn2
<selectname="xueli"> <optionvalue="">请选择学历</option> <optionvalue="大学">大学</option> <optionvalue="中学">中学</option> <optionvalue="初中">初中</option> <optionvalue="小学">小学</option> </select> <formaction=""> <p>Email:<inputtype="text"name="email"> 姓名:<inputtype="text"name="ming"> </p> </form>
document.getElementsByTagName('select')[0].onclick=function(){
alert('嘻嘻');
}
document.getElementsByName('email')[0].onblur=function(){
alert('哈哈哈');
}
window.onload=function(){
vard=document.getElementById('school');
functionfn1(){
alert('hello');
}
functionfn2(){
alert('world');
}
d.onclick=fn1;//赋值操作最终显示fn2
d.onclick=fn2;
}
绑定事件的第三种办法
//错误写法1
window.onload=function(){
vard=document.getElementById('school');
functionfn1(){//this此时指向window
this.style.background='blue';
}
functionfn2(){//this此时指向window
this.style.background='red';
}
//写一个匿名函数
//最终的出现错误
d.onclick=function(){
fn1();
fn2();
//fn1fn2是属性window的实际上是这样window.fn1()window.fn2()
}
}
下面这种写法没有问题但是给DOM树额外增加了两个变量
window.onload=function(){
vard=document.getElementById('school');
d.fn1=function(){//fn1是d的属性最终this此时指向DOM对象
this.style.background='blue';
}
d.fn2=function(){//this此时指向DOM对象
this.style.background='red';
}
//匿名函数调用上面两个函数
d.onclick=function(){
this.fn1();
this.fn2();
}
}
不在使用onclick
window.onload=function(){
vard=document.getElementById('school');
//达到了一次绑定两个函数
d.addEventListener('click',function(){alert('blue');this.style.background='blue'});
d.addEventListener('click',function(){alert('red');this.style.background='red'});
}
去除绑定不能用匿名函数匿名函数当时产生当时消失
varfn1=function(){alert('blue');this.style.background='blue'};
varfn2=function(){alert('red');this.style.background='red'};
functionadde(){
vard=document.getElementById('school');
d.addEventListener('click',fn1);
d.addEventListener('click',fn2);
}
functionreme(){
vard=document.getElementById('school');
//d.removeEventListener('click',fn1);//只剩fn1
d.removeEventListener('click',fn2);
}
在IE下第三种绑定事件的方法
<divid="school"> </div> <inputtype="button"value="加事件"onclick="adde();"> <inputtype="button"value="减事件"onclick="reme();">
varfn1=function(){alert('blue');this.style.background='blue'};
varfn2=function(){alert('red');this.style.background='red'};
functionadde(){
vard=document.getElementById('school');
//IE6,7是后绑定的事件先发生
d.attachEvent('onclick',fn1);
d.attachEvent('onclick',fn2);//fn2先发生
}
functionreme(){
vard=document.getElementById('school');
//d.deltachEvent('click',fn1);//只剩fn1
d.deltachEvent('click',fn2);
}
总结
以上就是JavaScript中绑定事件与去除绑定的三种方式,希望本文的内容对大家学习或者使用Javascript能有所帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。