---
title: "跨浏览器访问事件的方法"
author: "cakin24"
date: "2017-04-20T21:42:15Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2017-04-20T21:42:15Z"
id: 2370507
url: "https://cakin24.iteye.com/blog/2370507"
---

**一 介绍**

1、DOM事件模型和IE事件模型访问事件对象的方式完全不同，因此需要写一个跨浏览器的程序。

2、实现跨浏览器的通常做法是：将事件处理函数绑定到DOM对象的属性上。

 

**二 代码**

```
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 跨浏览器访问事件 </title>
</head>
<body>
	<button id="a">按钮</button>
	<script type="text/javascript">
	// 定义一个形参evt
	var clickHandler = function(evt)
	{
		// 对于DOM事件模型，访问事件源用target属性
		if (evt)
		{
			alert(evt.target.innerHTML);
		}
		// 对于IE浏览器
		else
		{
			alert(window.event.srcElement.innerHTML);
		}
	}
	// 为按钮a绑定事件处理器
	document.getElementById("a").onclick = clickHandler;
	</script>
</body>
</html>
```

 

**三 运行结果**

下面的运行结果分别是在谷歌浏览器和IE浏览器上执行的结果。

![](http://dl2.iteye.com/upload/attachment/0124/4712/cc64a68d-a207-30d0-8f35-38638ad3da64.png)