您的位置:首页 > Web前端 > JavaScript

JS preventDefault ,stopPropagation ,return false

2016-10-08 21:58 627 查看
所谓的事件有两种:监听事件和浏览器对特殊标签元素的默认行为事件。
监听事件:在节点上被监听的事件操作,如 select节点的change事件,a节点的click事件。
浏览器的默认事件:特定页面元素上带的功能,如a标签的href跳转,表单的提交事件。
执行监听事件在先,浏览器默认事件在后,所以可以在监听事件函数中,阻止浏览器的默认行为。
区别:preventDefault() 阻止浏览器默认事件  stopPropagation() 阻止事件的冒泡  return false; 阻止后续的所有行为


1 <!DOCTYPE html>
2 <html>
3 <head>
4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5     <title></title>
6     <script type="text/javascript">
7     //preventDefault,比如<a href='http://www.baidu.com'>百度</a>,preventDefault的作用就是阻止它的默认行为
8     function stoptDefault (e) {
9         if(e&&e.preventDefault){
10             e.preventDefault();
11         }
12         else{
13             window.event.returnValue=false;
14         }
15         return false;
16     }
17     window.onload=function(){
18         var test=document.getElementById("testLink");
19         test.onclick=function(e){
20         alert("我的连接地址是:"+this.href+',但是我不跳转');
21         stoptDefault(e);
22         }
23     }
24     //stopPropagation 阻止js事件冒泡
25
26     window.onload=function(){
27         var parent1=document.getElementById("parent1");
28         var childrent1=document.getElementById("childrent1");
29         parent1.onclick=function(){
30             alert(parent1.id)
31         };
32         childrent1.onclick=function(){
33             alert(childrent1.id)
34         };
35     }
36     function stopPro(obj,evt){
37         var e=(evt)?evt:window.event;
38         if(window.event){
39             e.cancelBubble=true;//ie下的阻止冒泡
40         }
41         else{
42             e.stopPropagation();//其他浏览器下的阻止冒泡
43         }
44     }
45     window.onload=function(){
46         var parent2=document.getElementById("parent2");
47         var childrent2=document.getElementById("childrent2");
48         parent2.onclick=function(){
49             alert(parent2.id)
50         };
51         childrent2.onclick=function(e){
52             stopPro(this,e);
53             alert(childrent2.id)
54         };
55     }
56     </script>
57 </head>
58 <body>
59 <a href="http://www.baidu.com" id="testLink">百度</a>
60 <br/>
61 <div id="parent1" style="width:250px;background-color:yellow">
62      <p>This is parent1 div.</p>
63      <div id="childrent1" style="width:200px;background-color:orange">
64          <p>This is Chilren1.</p>
65      </div>
66 </div>
67 <br/>
68 <div id="parent2" style="width:250px;background-color:cyan;">
69      <p>This is parent2 div.</p>
70      <div id="childrent2" style="width:200px;background-color:lightblue;">
71           <p>This is childrent2. Will bubble.</p>
72      </div>
73 </div>
74 </body>
75 </html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: