浅谈jQuery事件绑定原理

2020-05-22 17:11:35易采站长站整理

jq里面有一个data的方法,给dom元素绑定相关的数据的。当给dom用jq的方法绑定了事件,会生成对应的时间列表
可以看下面的例子(请在firefox中查看 因为firefox中对象支持toSource())


<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />
<title></title>
</head>
<body>
<div id=”test”></div>
<script type=”text/javascript” src=”http://common.cnblogs.com/script/jquery.js”></script>
<script type=”text/javascript”>
    window.onload = function(){
        alert($.data($(‘#test’)[0],’events’));//null
        alert($.data($(‘#test’)[0],’handle’));//null
        $(‘#test’)
        .bind(‘click’,function(){
            alert(1)
        })
        .bind(‘mouseover’,function(){
            alert(2)
        })
        .bind(‘click’,function(){
            alert(3)
        })
        .bind(‘click’,function(){
            alert(4)
        })
        alert($.data($(‘#test’)[0],’events’).toSource());//时间列表
        alert($.data($(‘#test’)[0],’handle’).toSource());//执行的函数
    }
</script>
</body>
</html>
 
data是给元素绑定数据的
数据源是 cache对象
当元素绑定数据的时候 会给元素添加一个属性   jQueryxxx      xxx为执行jq的时间戳
这里要说明一下,有一个uuid 他是累加的
jQueryxxx的值就是这个uuid
cache 的 key就是这个 uuid
value就是要存的数据
data对于事件的绑定是很重要的…………………………..


function now(){ 
    return +new Date; 
};
var win     = this,
    expando = “jQuery” + now(), 
       uuid    = 0,