JS(十二)

来源:互联网 发布:it is essential that 编辑:程序博客网 时间:2024/06/01 08:24

冒泡事件

(1)冒泡就是后代元素的事件被触发的时候,其祖先元素的相同事件也会被触发;冒泡是向上导向的;

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">#box1{width: 300px;height: 300px;background-color: #00BFFF;}#s1{background-color: yellow;}</style><script type="text/javascript">window.onload=function(){var box1=document.getElementById("box1");var s1=document.getElementById("s1");var body=document.body;//冒泡就是后代元素的事件被触发的时候,其祖先元素的相同事件也会被触发;冒泡是向上导向的//如果我们不需要冒泡,可以通过事件对象来取消冒泡;box1.onclick=function(){alert("box1");}s1.onclick=function(event){//event.cancelBubble=true;//可以通过cancelBubblealert("s1");}body.onclick=function(){alert("body");}};</script></head><body><div id="box1">我是div<span id="s1">我是span</span></div></body></html>

//冒泡的练习;

事件的委派

 

事件的委派:通过冒泡的方式来解决,多次创建响应事件的问题,我们可以对同一事件的祖先元素绑定,通过冒泡来解决,后代元素绑定事件的问题;

Event 事件对象的target属性用来表示触发事件对象;

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">.box1{width: 400px;height: 200px;background-color: aquamarine;}</style><script type="text/javascript">window.onload=function(){//获取超链接var ul=document.getElementById("s1");var lias=document.getElementsByTagName("a");var bnt01=document.getElementById("btn01");//为a绑定一个事件//for(var i=0;i<lias.length;i++)//{//lias[i].onclick=function(){//alert("超链接");//};////}bnt01.onclick=function(){//创建超链接;var li=document.createElement("li");li.innerHTML="<a href='#' class='sn'>新建超链接</a>";ul.appendChild(li);}ul.onclick=function(event){//只有点击超链接的时候才执行,其他的地方不执行;if(event.target.className=="sn")   alert("超链接");}};</script></head><body><button id="btn01">创建一个超链接</button><div class="box1"><ul id="s1" style="background-color:red ;"><li><a href="#" class="sn">超链接一</a></li><li><a href="#" class="sn">超链接二</a></li><li><a href="#" class="sn">超链接三</a></li></ul></div></body></html>



原创粉丝点击