---
title: "javascript中阻止浏览器的默认操作"
author: "xide829"
date: "2010-05-18T22:03:34Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2010-05-18T22:03:34Z"
id: 669359
url: "https://xide829.iteye.com/blog/669359"
---

最近学习了一些关于JavaScript事件方面的知识，把它们记录下来，用于将来用时查询。

1、阻止浏览器默认操作。

```
<script type="text/javascript">  
	function stopDefault( e ) {     
		//适用于火狐等实现了W3C规范的浏览器     
 		if ( e && e.preventDefault )         
 			e.preventDefault();     
 		//适用于IE    
 		else        
 			window.event.returnValue = false;     
 		return false; 
 	}
</script>  
<a href="http://www.google.com" id="testLink">Google</a>  
<script type="text/javascript"> 
 	var test = document.getElementById('testLink'); 
 	test.onclick = function(e) {     
 		alert('我的链接地址是：' + this.href + ', 但是我不会跳转。');     
 		stopDefault(e); 
 	} 
</script>  
```

  2、阻止事件冒泡

```
    /*---------------------------
    功能:停止事件冒泡
    ---------------------------*/
    function stopBubble(e) {
        //如果提供了事件对象，则这是一个非IE浏览器
        if ( e && e.stopPropagation )
            //因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        else
            //否则，我们需要使用IE的方式来取消事件冒泡
            window.event.cancelBubble = true;
    }
```

 

待续。。。。