首页 > 语言 > JavaScript > 正文

jquery绑定原理 简单解析与实现代码分享

2024-05-06 14:23:45
字体:
来源:转载
供稿:网友
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,
cache = {};
win.data = function(elem, name, data){
var id = elem[expando];
if(!id)
id = elem[expando] = ++uuid;
if(name&&!cache[id])
cache[id] = {};
if(data !== undefined)
cache[id][name] = data;
return name
? cache[id][name]
: id;
}
win.removeData = function(elem, name){
var id = elem[expando];
if (name){
if (cache[id]) {
delete cache[id][name];
name = "";
for ( name in cache[ id ] )
break;
if ( !name )
removeData(elem);
}
}else{
try {
delete elem[expando];
} catch(e){
if ( elem.removeAttribute )
elem.removeAttribute( expando );
}
delete cache[id];
}
}
win.each = function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选