JavaScript:向EventListener传递多个参数和事件

5

我想通过addEventListener方法向按钮添加EventListener。以下是代码:

myElement[i].addEventListener('click', buttonLink);

这个很好用,它将事件作为一个值传递给方法。这是方法头:

function buttonLink(e) {
    //Now i can access the srcElement via:
    e.srcElement.id ...
}

问题是,如果我向该方法传递参数,则会隐藏e参数,并且在方法内部完全看不到它。 有没有一种方法可以将我的值和事件一起传递给事件监听器?
谢谢。
3个回答

5
将匿名函数传递给 addEventListener 并从其中调用回调函数:
myElement[i].addEventListener('click', function (e) {
    buttonLink(e, somethingElse, anotherThing);
});

3
虽然这是好的,但在使用removeEventListener时不起作用,因为您将无法删除此匿名处理程序。 - chrisdotcode

3

下面我给出了两种传递函数参数的方法。这两种方法都适用于 addEventListenerremoveListener

方法1:包装函数:

let myElement = document.getElementById('myId');
function wrapperFunction(e) { 
    myFunction(e, 5, 9); //define your function and pass arguments(5,9)
}

myElement.addEventListener('event', wrapperFunction);
myElement.removeEventListener('event', wrapperFunction);

注意:'e'事件是从'addEventListener'函数免费获得的。
方法2:柯里化。
var myFunction = function (arg1, arg2) {
    return function curriedFunc(e) {
      myFunction(e, arg1, arg2); // define your function and pass arguments(5,9)
    };
};

let myElement = document.getElementById('myId');
let myRef = myFunction(5,9);
myElement.addEventListener('click', myRef);
myElement.removeEventListener('click', myRef);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接