JS preventDefault ,stopPropagation ,return false
2015-07-30 11:36
806 查看
所谓的事件有两种:监听事件和浏览器对特殊标签元素的默认行为事件。 监听事件:在节点上被监听的事件操作,如 select节点的change事件,a节点的click事件。 浏览器的默认事件:特定页面元素上带的功能,如a标签的href跳转,表单的提交事件。 执行监听事件在先,浏览器默认事件在后,所以可以在监听事件函数中,阻止浏览器的默认行为。 区别:preventDefault() 阻止浏览器默认事件 stopPropagation() 阻止事件的冒泡 return false; 阻止后续的所有行为
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript"> //preventDefault,比如<a href='http://www.baidu.com'>百度</a>,preventDefault的作用就是阻止它的默认行为 function stoptDefault (e) { if(e&&e.preventDefault){ e.preventDefault(); } else{ window.event.returnValue=false; } return false; } window.onload=function(){ var test=document.getElementById("testLink"); test.onclick=function(e){ alert("我的连接地址是:"+this.href+',但是我不跳转'); stoptDefault(e); } } //stopPropagation 阻止js事件冒泡 window.onload=function(){ var parent1=document.getElementById("parent1"); var childrent1=document.getElementById("childrent1"); parent1.onclick=function(){ alert(parent1.id) }; childrent1.onclick=function(){ alert(childrent1.id) }; } function stopPro(obj,evt){ var e=(evt)?evt:window.event; if(window.event){ e.cancelBubble=true;//ie下的阻止冒泡 } else{ e.stopPropagation();//其他浏览器下的阻止冒泡 } } window.onload=function(){ var parent2=document.getElementById("parent2"); var childrent2=document.getElementById("childrent2"); parent2.onclick=function(){ alert(parent2.id) }; childrent2.onclick=function(e){ stopPro(this,e); alert(childrent2.id) }; } </script> </head> <body> <a href="http://www.baidu.com" id="testLink">百度</a> <br/> <div id="parent1" style="width:250px;background-color:yellow"> <p>This is parent1 div.</p> <div id="childrent1" style="width:200px;background-color:orange"> <p>This is Chilren1.</p> </div> </div> <br/> <div id="parent2" style="width:250px;background-color:cyan;"> <p>This is parent2 div.</p> <div id="childrent2" style="width:200px;background-color:lightblue;"> <p>This is childrent2. Will bubble.</p> </div> </div> </body> </html>
相关文章推荐
- js 根据年月获取当月有多少天_js获取农历日期_及Js其它常用有用函数
- Javascript事件冒泡机制
- Js中判断一个值为null
- 用javascript写的加法运算的两种方法
- js代码实现随机颜色的小方块
- js代码验证手机号码和电话号码是否合法
- Ubuntu 安装 jsoncpp的全过程
- Jsp在Web.xml中的配置
- extjs Grid的表头要跟着需求刷新
- js插件收藏&&开发辅助工具
- jsp页面charset与head中charset的区别
- Javascript处理JSON数据格式
- JavaScript之基本介绍
- 用javascript预加载图片、css、js的方法研究
- js 对象深复制,创建对象和继承
- 使用velocity.js制作炫酷滚动效果页面
- javascript设计模式之对象工厂函数与构造函数详解
- json kit
- js
- javascript收集连接