我想创建一个传递事件和一些参数的eventHandler.问题是函数没有得到元素.这是一个例子:
doClick = function(func){
var elem = .. // the element where it is all about
elem.onclick = function(e){
func(e, elem);
}
}
doClick(function(e, element){
// do stuff with element and the event
});
Run Code Online (Sandbox Code Playgroud)
'elem'必须在匿名函数之外定义.如何在匿名函数中获取传递的元素?有没有办法做到这一点?
那么addEventListener呢?我似乎无法通过addEventListener传递事件吗?
更新
我好像用'这个'解决了这个问题
doClick = function(func){
var that = this;
this.element.onclick = function(e){
func(e, that);
}
}
Run Code Online (Sandbox Code Playgroud)
这包含我可以在函数中访问的this.element.
addEventListener
但我想知道addEventListener:
function doClick(elem, func){
element.addEventListener('click', func(event, elem), false);
}
Run Code Online (Sandbox Code Playgroud)