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

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: