Doc10(this,事件冒泡)

来源:互联网 发布:002348是人工智能吗 编辑:程序博客网 时间:2024/06/05 17:25

this的区别

this是谁触发的方法,谁就是this这个对象.
实例:

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>Document</title>  <script type='text/javascript'>  f1=function(){      window.id='78';alert(this.id); //这样子打印出来的是window的id  };  </script> </head> <body>  <input id='btnC' type='button' name='name' value='按钮' onclick='f1();' > </body></html>

而下面这个例子讲的更为清晰

事件冒泡

事件冒泡指的是当事件发生后,事件传播后出现多个事件结果,一般情况下需要阻止事件冒泡(注意使用retrun false失败).
实例:

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>Document</title>  <style type='text/css'>  div  {width:200px;height:300px;background-color:yellow;cursor:pointer;  }  p  {  width:150px;  height:200px;  background-color:green;cursor:pointer;  }  span  {  background-color:orange;  cursor:pointer;  }  </style><script type='text/javascript'>onload=function(){document.getElementById('dv').onclick=function(){//alert(this.id);//谁触发的this就是他对象 alert(event.srcElement.id);//记录的是谁最开始触发的//event.cancelBubble=true;//取消事件冒泡};document.getElementById('p1').onclick=function(){//alert(this.id);alert(event.srcElement.id);//event.cancelBubble=true;};document.getElementById('sp').onclick=function(){//alert(this.id)alert(event.srcElement.id);//event.cancelBubble=true;};};</script> </head> <body>  <div id='dv'><p id='p1'><span id='sp'> this is span</span></p>  </div> </body></html>

在实例中,使用 cursor:pointer
来达到鼠标移动到该内容上时变成一个小手
cursor:光标 pointer:指针,指示器
使用event.srcElement
来记录最开始触发的对象.
使用event.canelBubble=true;
来取消事件冒泡.否则还是会弹出多个窗口,中间的内容会相同.但是需要注意的是,在火狐中不支持event,故改方法无法火狐中直接运行.

0 0
原创粉丝点击