zoukankan      html  css  js  c++  java
  • 给事件响应函数传参数的多种方式

    如何给事件handler传参数?在刚刚接触Javascript的时候,由于对闭包理解不深刻,常常纠结于该问题。

    在讨论群里也经常碰到这样的问题,如下

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="utf-8">
        <title>如何给事件handler传参数?</title>
    </head>
    <body>
    	<a href="#" id="aa">Click me</a>
    	<script type="text/javascript">
    		var E = {
    			on : function(el, type, fn){
    				el.addEventListener ?
    					el.addEventListener(type, fn, false) :
    					el.attachEvent("on" + type, fn);
    			},
    			un : function(el,type,fn){
    				el.removeEventListener ?
    					el.removeEventListener(type, fn, false) :
    					el.detachEvent("on" + type, fn);		
    			}
    		};
    		
    		var v1 = 'jack', v2 = 'lily';						
    		function handler(arg1,arg2){
    			alert(arg1);
    			alert(arg2);
    		}
    				
    		// 如何把参数v1,v2传给handler?
    		// 默认事件对象将作为handler的第一个参数传入,
    		// 这时点击链接第一个弹出的是事件对象,第二个是undefined。				
    		E.on(document.getElementById('aa'),'click',handler);
    	</script>
    </body>
    </html>
    

    如何把参数v1,v2传给handler?默认事件对象将作为handler的第一个参数传入,这时点击链接第一个弹出的是事件对象,第二个是undefined。


    方案一 ,未保留事件对象作为第一个参数传入

    function handler(arg1,arg2){
    	alert(arg1);
    	alert(arg2);
    }
    E.on(document.getElementById('aa'),'click',function(){	
    	handler(arg1,arg2);	
    });
    

    方案二,保留事件对象作为第一个参数 

    function handler(e,arg1,arg2){
    	alert(e);
    	alert(arg1);
    	alert(arg2);
    }
    E.on(document.getElementById('aa'),'click',function(e){
    	handler(e,arg1,arg2);
    });
    

    方案三,给Function.prototype添加getCallback,不保留事件对象

    Function.prototype.getCallback = function(){
    	var _this = this, args = arguments;		
    	return function(e) {
            return _this.apply(this || window, args);
        };
    }
    E.on(document.getElementById('aa'),'click',handler.getCallback(v1,v2));
    

    方案四,给Function.prototype添加getCallback,保留事件对象作为第一个参数传入

    Function.prototype.getCallback = function(){
    	var _this = this, args = [];
    	for(var i=0,l=arguments.length;i<l;i++){
    		args[i+1] = arguments[i];
    	}
    	return function(e) {
    		args[0] = e;
            return _this.apply(this || window, args);
        };
    }
    E.on(document.getElementById('aa'),'click',handler.getCallback(v1,v2));
    
  • 相关阅读:
    web.xml中load-on-startup的作用
    Spring加载resource时classpath*:与classpath:的区别
    免费svn远程仓库推荐
    学习websocket
    eclipse下的maven
    maven常用命令
    文件操作的补充
    模块
    正则表达式,计算器,装饰器,冒泡排序,用户登录系统
    拷贝,集合,函数,enumerate,内置函数
  • 原文地址:https://www.cnblogs.com/snandy/p/1994184.html
Copyright © 2011-2022 走看看