情况有点像

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。


当前回答

不错的一行选择

element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {

 //some action...

}

其他回答

也可以试试这些(IE8 + Chrome。我不知道FF):

function addEvent(obj, type, fn) {
    eval('obj.on'+type+'=fn');
}

function removeEvent(obj, type) {
    eval('obj.on'+type+'=null');
}

// Use :

function someFunction (someArg) {alert(someArg);}

var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};

// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive

希望没有拼写错误:-)

完美的解决方案是使用闭包,像这样:

function makeSizer(size) { return function () { document.body.style.fontSize = `${size}px`; }; } //pass parameters here and keep the reference in variables: const size12 = makeSizer(12); const size24 = makeSizer(24); const size36 = makeSizer(36); document.getElementById('size-12').addEventListener("click", size12); document.getElementById('size-24').addEventListener("click", size24); document.getElementById('size-36').addEventListener("click", size36); document.getElementById('remove-12').addEventListener("click", ()=>{ document.getElementById('size-12').removeEventListener("click", size12); alert("Now click on 'size 12' button and you will see that there is no event listener any more"); }); test<br/> <button id="size-12"> size 12 </button> <button id="size-24"> size 24 </button> <button id="size-36"> size 36 </button> <button id="remove-12"> remove 12 </button>

因此,基本上你将一个函数包装在另一个函数中,并将其分配给一个变量,你可以注册为事件侦听器,但也可以取消注册!

一个简单的方法就是这样

    window.addEventListener('click', (e) => functionHandler(e, ...args));

对我有用。

如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。

在下面的代码中,我将说明我的意思。

// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
  console.log('we get our custom input', foo, bar);
  console.log('we get the click event too', clickEvent);
}

// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler


const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);

// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);

下面是CodePen上的一个工作示例

这里还有另一种方法(它在for循环中工作):

var someVar = some_other_function();
someObj.addEventListener("click", 

function(theVar){
    return function(){some_function(theVar)};
}(someVar),

false);