---
title: "JS阻止事件冒泡和阻止浏览器默认行为"
author: "hello_world_hello"
date: "2015-05-18T23:24:42Z"
tags: []
categories: ["编程语言"]
slug: "js"
draft: false
lastmod: "2015-05-22T23:14:41Z"
id: 2212305
url: "https://hello-world-hello.iteye.com/blog/2212305"
---

1. 事件冒泡：父元素和子元素注册了相同的事件，当事件触发时，事件逐层向底元素传递，最底层元素先处理该事件，然后交给父元素处理。  
   举例：
   
   ```
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Insert title here</title>
   
   </head>
   <body>
   	<div onclick="parent(event);" style="height: 200px;width: 200px;background-color: green;">
   		<div onclick="child(event);" style="height: 100px;width: 100px; background-color: red"></div>
   	</div>
   </body>
   </html>
   <script type="text/javascript">
   	function parent(event) {
   		alert("父元素");
   	}
   	
   	function child(event) {
   		alert("子元素");
   	}
   </script>
   ```
   
    单击子div时，先弹出子元素对话框，然后弹出父元素对话框，这说明事件是向上冒泡的。
   
   有时我们不想事件向上冒泡，只希望子元素处理该事件，这是我们可以通过事件对象event的stopPropagation()来实现。
   
   ```
   	function child(event) {
   		alert("子元素");
   		event.stopPropagation();
   	}
   ```
2. 阻止浏览器的默认行为

     单击超链接除了处罚onclick事件外浏览器还有默认的行为那就是打开href的链接，还有单击提交按钮时除     了onclick事件外还有表单提交等浏览器默认行为。

     阻止浏览器的默认行为的方式有：1） onclick事件返回false; 2) 调用事件对象event.preventDefault();方法

```
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

</head>
<body>
	<a href="http://www.baidu.com" onclick="return false;">test1</a><br/>
	<a href="http://www.baidu.com" onclick="test2();">test2</a><br/>
</body>
</html>
<script type="text/javascript">
	function test2() {
		event.preventDefault();
	}
</script>
```

 单击test1和test2都不进行跳转。