码迷,mamicode.com
首页 > 其他好文 > 详细

自定义事件

时间:2015-08-05 19:50:36      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

window.onload = function(){
	var oDiv = document.getElementById(‘div1‘);
	var oSpan = document.getElementById(‘span1‘);
	
	bindEvent(oDiv , ‘click‘,function(){
		alert(1);
	});
	
	bindEvent(oDiv , ‘click‘,function(){
		alert(2);
	});
	
	bindEvent(oSpan , ‘show‘,function(){
		alert(3);
	});
	
	bindEvent(oSpan , ‘show‘,function(){
		alert(4);
	});
	
	bindEvent(oSpan , ‘hide‘,function(){
		alert(5);
	});
	
	
	fireEvent(oSpan , ‘show‘);  //3 , 4
	
};

function bindEvent(obj,events,fn){
	//obj : 楼层
	//events : 书架
	//fn : 一本书
	
	obj.listeners = obj.listeners || {};
	obj.listeners[events] = obj.listeners[events] || [];
	
	obj.listeners[events].push( fn );
	
	
	if(obj.addEventListener){
		obj.addEventListener(events,fn,false);
	}
	else{
		obj.attachEvent(‘on‘+events,fn);
	}
}

function fireEvent(obj,events){   //主动触发自定义事件
	
	for(var i=0;i<obj.listeners[events].length;i++){
		 obj.listeners[events][i]();
	}
	
}

</script>
</head>

<body>
<div id="div1">div</div>
<span id="span1">span</span>
</body>
</html>

  

自定义事件

标签:

原文地址:http://www.cnblogs.com/yanwen2015/p/4705412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!