js中
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button>点击</button>
<a href="##" target="_blank">跳到新的空白页</a>
<script type="text/javascript">
var a=document.getElementsByTagName("a")[0];
var btn = document.getElementsByTagName("button")[0];
a.onclick=function(){
return false;//阻止a的默认行为
}
btn.onclick = function() {
alert(1);
return false;
}
document.body.onclick = function() {
alert(1);
}
</script>
</body>
</html>
//弹出了2次警告框输出1
jquery中
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button>点击</button>
<a href="##" target="_blank">跳到新的空白页</a>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function() {
$("a").click(function(){
return false;//阻止默认行为
});
$("button").click(function() {
alert(1);
return false;//阻止默认行为和冒泡
});
$(document).click(function() {
alert(1);
});
})
</script>
</body>
</html>
//结果只有一次警告框输出1