对于冒泡和捕捉事件,其实我们可以理解为,当我们当前点击的事件本身的父元素也绑定了冒泡事件和捕捉事件的时候,我们才会看的出区别,如果我们点击元素的父元素根本没有绑定事件
b2.addEventListener('click',function(){alert("b2在冒泡阶段被点击啦"),false})
b2.addEventListener('click',function(){alert("b2在捕获阶段被点击啦"),true})
a8.addEventListener("click",function(){alert("a8在捕获阶段被点击啦")},true)
a8.addEventListener("click",function(){alert("a8在冒泡阶段被点击啦")},false)
body.addEventListener("click",function(){alert("body在冒泡阶段被点击啦")},false)
body.addEventListener("click",function(){alert("body在捕获段被点击啦")},true)
parent.addEventListener("click",function(){alert("parent在捕获阶段被点击啦")},true)
parent.addEventListener("click",function(){alert("parent在冒泡阶段被点击啦")},false)
1.button 元素的默认type=="submit"
eg:<button onclick="alert(this.type)"></button>
dom0级 onclick=handler
html 绑定 <input type="button" onclick="alert(this)">
dom2级 div.addEventListener("click",show(this),false) this 都指向元素本身
div.attachEvent("onclick",function(){console.log(this===window)})
。在使
用 DOM0 级方法的情况下,事件处理程序会在其所属元素的作用域内运行;在使用 attachEvent()方
法的情况下,事件处理程序会在全局作用域中运行,因此 this 等于 window。
DOM0 级对每个事件只支持一
个事件处理程序。
当在当前元素绑定
body.addEventListener("click",function(event){console.log(this);console.log(event.srcElement);console.log(event.currentTarget)},true)
event.srcElement 指向事件触发的元素 event.currentTarget 指向事件绑定的元素 this指向事件绑定的元素
引出事件委托
3.stopPropagation与stopImmediatePropagation异同
stopPropagation()阻止事件继续捕获或者冒泡,
stopImmediatePropagation 阻止事件继续捕获或者冒泡及该元素后面绑定的事件
body.onclick=function(){alert("clicked body")}
addBtn.addEventListener("click",handler,true);
addBtn.addEventListener("click",function(){alert("no propagation")},true);
addBtn.addEventListener("click",function(){alert("no immedatepropagation")},true);
addBtn.addEventListener("mouseout",function(){alert("no propagation")},true);
addBtn.addEventListener("mouseenter",handler,true);
}
var handler=function(event){
switch(event.type){
case "click":console.log("ds");event.stopImmediatePropagation()
break;
case "mouseout":event.srcElement.innerText="mouseout";
break;
case "mouseenter":event.srcElement.innerText="mouseener"
}
}