js事件绑定 onclick && addEventListener

来源:互联网 发布:闪电网络 原理 编辑:程序博客网 时间:2024/05/16 11:05
昨晚回去后,和雷子讨论如何才能“检测”到页面上某个元素都绑定了哪些事件监听函数,第一感觉就是应该从浏览器入手,比如FF,或者Chrome等
开发工具中应该有相应的功能,于是测试之: 
前提:只是一个简单的小测试,而且 addEventListener 属于标准绑定函数,IE 中与此不兼容(IE 相应的是 attachEvent),所以此次测试先抛弃 IE,使用 Firefox 5.0.1, Chrome 14.0, Opera 11.50 
测试页面: 
复制代码代码如下:

<!DOCTYPE html> 
<html> 
<head> 
<title>Test</title> 
<style type="text/css"> 
.test { 
background-color: #FFF; 
border: 1px solid gray; 
height: 100px; 
width: 100px; 
margin: 0 10px 0; 
float: left; 

</style> 
</head> 
<body> 
<div id="test1" class="test" onclick="console.log('test1 : click!');" onmouseover="console.log('test1 : mouseover!');">TEST1</div> 
<div id="test2" class="test">TEST2</div> 
<div id="test3" class="test">TEST3</div> 
<script type="text/javascript"> 
(function(){ 
var $ = function(o){//Simple Tool 
return document.getElementById(o); 

//For Test2: 
$('test2').onclick = function(){console.log('test2 : click!');} 
$('test2').onmouseover = function(){console.log('test2 : mouseover!');} 
//For Test3: 
$('test3').addEventListener('click', function(){ 
console.log('test3 : click!'); 
}, false); 
$('test3').addEventListener('mouseover', function(){ 
console.log('test3 : mouseover!'); 
}, false); 
})(); 
</script> 
</body> 
</html> 

页面效果如下截图:

 

测试代码中采用了三种最常见的事件绑定方法

FIREFOX:

1,Firefox 的 Firebug 中选中 test1 元素:

image

右侧 DOM 标签中选择显示所有属性:

image

在其中找到了 attributes 数组,如下:

image

这是因为 test1 元素的两个事件句柄直接写到了元素中,再往下的列表中找不到更多相关的信息,此种绑定模式下只能在 firebug 的 DOM 标签的 attributes 中找到事件句柄。

2,选中 test2 元素:

image

右侧 DOM 标签:

image

test2 采用在 javascript 中绑定事件句柄的方式,被作为“用户自定义属性”显示在了 DOM 标签中,右击鼠标可以查看相关信息:

image

3,选中 test3 元素:

image

这次在 DOM 标签中没有找到任何相关此元素绑定事件的信息。。。

总而言之,firebug 中在标准绑定事件函数下(addEventListener),并不好检测到某个元素已绑定的事件函数,(不要说尝试打印一下那个元素的 onclick 属性,addEventListener 绑定和 onclick 绑定毫不相干,此种情况下你会得到 nudefined);如果是在前两种事件绑定下,可以得到一些简单信息。

-----

OPERA:

1,在 Opera 的 Dragonfly 中选中 test1 :

image

在右方的属性列表中可以找到相关的信息:

image

点击加号同样可以查看绑定的函数信息:

image

想查看某个函数体的话,有一种简单的方法,在控制台中直接输入:

image

直接就打印出函数体,更加的方便!

2,选择 test2  test1 几乎相同,就不在赘述了;

3,选择 test3:

image

右方的属性标签里找不到什么了,onclick 和 onmouseover 的值都为 null。

总而言之,Opera Dragonfly 和 Firefox Firebug 表现差不多,对在标准绑定函数下 某个元素绑定了哪些事件表达得不是很清晰。

-----

CHROME:

Chrome 下就清晰很多了:

1,在调试工具中选择 test1(或者 test2,这两者类似)

image

看看右侧的信息位:

image

Chrome 中的 Event Listeners 是一个不错的小工具,直接罗列出当前选中元素上面已经被绑定的监听函数,点击小黑三角可以查看绑定函数的信息:

image

click 中有两项,第一项是 div#test1,这个就是我们绑定的 onclick 函数信息;第二项的 document 可以不去看(Chrome 自身的处理);

isAttribute: true :说明此 onclick 函数句柄是作为元素属性来对待的(因为我们用的是 onclick = function(){…},不管是 test1 还是 test2);

lineNumber: 18 :说明绑定函数的位置;

useCapture: false : 说明不使用事件捕获;其他的语义性很强,就不说了;

同样,在 Properties 的第一个 HTMLDivElement 列表中,test1 和 test2 中都能看到:

image

2,选中 test3

image

在 Properties 中 onclick 和 onmouseover 都会变成 null,但是 Event Listeners 仍旧是:

image

但是注意这里的 div#test3:

image

isAttribute 变成了 false,因为我们没有使用 onclick 属性,而是用的 addEventListener。


转自:http://www.jb51.net/article/27848.htm

0 0
原创粉丝点击