javascript事件绑定

本文介绍了一种优化事件绑定的跨浏览器兼容性实现方法,通过创建绑定函数和兼容性绑定事件函数列表,确保事件绑定在不同浏览器中都能正常工作。实现了只判断一次浏览器兼容性的目标,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做事件绑定的时候要考虑浏览器的兼容性,每次绑定事件时都要去判断下当前浏览器是支持哪一种绑定方法,其实可以做到只判断一次。


实现事件绑定代码片段:

1) 首先创建绑定函数,确定必要参数。

bind: function(target, type, callback){
//实现逻辑...
}

2)创建兼容性绑定事件函数列表。

					var methods = [
						function(target, type, callback){ target.addEventListener(type, callback, false); },
					 	function(target, type, callback){ target.attachEvent('on'+type, callback); }
					 ];

主是要IE与非IE。

3)找到当前浏览器所支持的事件函数。

					for(var i=0, len=methods.length; i<len; i++){
						try{
							methods[i](target, type, callback);
						}catch(e){
							continue;
						}
						
						this.bind = methods[i];
						return methods[i];
					}

这里有一点很重要,当找到合适的事件函数时,重置bind方法,这样就确保事件函数判断只会执行一次。

this.bind = methods[i];

删除事件也可以这样实现。


送上完整代码:

			var Event = function(){};
			Event.prototype = {
				bind: function(target, type, callback){
					var methods = [
						function(target, type, callback){ target.addEventListener(type, callback, false); },
					 	function(target, type, callback){ target.attachEvent('on'+type, callback); }
					 ];
					
					for(var i=0, len=methods.length; i<len; i++){
						try{
							methods[i](target, type, callback);
						}catch(e){
							continue;
						}
						
						this.bind = methods[i];
						return methods[i];
					}
				},
				unbind: function(target, type, callback){
					var methods = [
						function(target, type, callback){ target.removeEventListener(type, callback, false); },
					 	function(target, type, callback){ target.dettachEvent('on'+type, callback); }
					 ];
					
					for(var i=0, len=methods.length; i<len; i++){
						try{
							methods[i](target, type, callback);
						}catch(e){
							continue;
						}
						
						this.bind = methods[i];
						return methods[i];
					}
				}
			}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值