1.解绑事件的方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件的绑定及解绑地三种方式(附兼容代码)</title>
</head>
<body>
<script src="common.js"></script>
<input type="button" value="点击" id="btn" />
<input type="button" value="解绑第一个事件" id="btn2" />
<script>
//第一种方式:绑定及解绑--对象.on方式
// my$("btn").onclick=function () {
// console.log("第一个");
// }
// my$("btn2").onclick=function () {
// my$("btn").onclick=null;//指定空
// }
//第二种方式:绑定及解绑--
// addeventListener(没有on的事件类型,命名事件处理函数,布尔类型(一般是false))
// 谷歌和火狐支持
// function fistTo() {
// console.log("第一");
// }
// function twoFi() {
// console.log("第二个");
// }
// my$("btn").addEventListener("click",fistTo,false);//绑定第一个
// my$("btn").addEventListener("click",twoFi,false);//绑定第二个
// my$("btn2").onclick=function(){
// my$("btn").removeEventListener("click",fistTo,false);//点击后解绑
// }
//第三种方式:绑定及解绑--
// attachEvenet(on的事件类型,命名事件处理函数,布尔类型(一般是false))
// IE8
// function twoFi() {
// console.log("第二个");
// }
// my$("btn").attachEvenet("onclick",fistTo,false);//绑定第一个
// my$("btn").attachEvenet("onclick",twoFi,false);//绑定第二个
// my$("btn2").onclick=function(){
// my$("btn").detachEvenet("onclick",fistTo,false);//点击后解绑
// }
//为任意一个元素绑定事件:元素,事件类型,事件处理函数
function addEventListener(element,type,fn) {
if(element.addEventListener){
//支持
element.addEventListener(type,fn,false);
}else if(element.attachEvent){
element.attachEvent("on"+type,fn);
}else{
element["on"+type]=fn;
}
}
//为任意的一个元素解绑某个事件:元素,事件类型,事件处理函数
function removeEventListener(element,type,fn) {
if(element.removeEventListener){
element.removeEventListener(type,fn,false);
}else if(element.detachEvent){
element.detachEvent("on"+type,fn);
}else{
element["on"+type]=null;
}
}
</script>
<script></script>
</body>
</html>
2.事件冒泡及阻止
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#dt1{
width:400px;
height:400px;
background-color: red;
}
#dt2{
width:200px;
height:200px;
background-color: blue;
}
p{
width:100px;
height:100px;
background-color: green;
}
</style>
</head>
<body>
<div id="dt1">
<div id="dt2">
<p id="pt"></p>
</div>
</div>
<script src="common.js"></script>
<script>
//事件冒泡--多个元素嵌套,有层次关系都注册了相同事件,如果里面元素地元素事件触发,外面元素 的事件也触发
//阻止事件冒泡方式有二个:
// 1.window.event.cancelBubble=true;
//2.e.stoppropagation
my$("dt1").onclick=function () {
console.log(this.id);
}
my$("dt2").onclick=function () {
window.event.cancelBubble=true;//IE特有 谷歌支持,火狐不支持--阻止事件冒泡
console.log(this.id);
}
my$("pt").onclick=function (e) {
e.stopPropagation();//谷歌和火狐支持--阻止事件冒泡
console.log(this.id);
}
</script>
</body>
</html>