给事件响应函数传参数的四种方式小结
作者:互联网
2025-07-30
如何给事件handler传参数?在刚刚接触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);
如何把参数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 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));
相关标签:
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
「性能优化」虚拟列表极致优化实战:从原理到源码,打造丝滑滚动体验
你的 Vue 3 生命周期,VuReact 会编译成什么样的 React?
你的 Vue 3 defineProps(),VuReact 会编译成什么样的 React?
Vue条件渲染详解:v-if、v-show用法与实战指南
前端性能内卷终点?Signals 正在重塑我们的开发习惯
使用 IntersectionObserver + 哨兵元素实现长列表懒加载
大屏卡成 PPT?这 3 个性能优化招数亲测有效
别再用 JSON.parse 深拷贝了,聊聊 StructuredClone
当 Vue 3 遇上桥接模式:手把手教你优雅剥离虚拟滚动的业务大泥球
VueUse 全面指南|Vue3组合式工具集实战
AI精选
