情况有点像

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

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


当前回答

下面的方法对我很有效。从这里修改。

函数回调(theVar) { 返回函数(){ theVar (); } } 函数some_other_function() { document.body.innerHTML += "made it."; } var someVar = some_other_function; . getelementbyid(“按钮”)。addEventListener(“点击”,回调(someVar)); <!DOCTYPE html > < html > 身体< > <button type="button" id="button">点击我!< / >按钮 < /身体> < / html >

其他回答

如果以后想要删除事件侦听器,那么创建对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上的一个工作示例

如果我没有弄错的话,使用bind调用函数实际上创建了一个由bind方法返回的新函数。这将在以后给你带来问题,或者如果你想删除事件监听器,因为它基本上就像一个匿名函数:

// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);

// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);

记住这一点。

如果你正在使用ES6,你可以按照建议做,但更干净一点:

someObject.addEventListener('event', () => myCallback(params));

在所有函数中都有一个特殊的变量:参数。您可以将参数作为匿名参数传递,并通过arguments变量(按顺序)访问它们。

例子:

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

为什么不直接从事件的目标属性获取参数呢?

例子:

const someInput = document.querySelector('button'); someInput。addEventListener('click', myFunc, false); someInput。myParam = '这是我的参数'; 函数myFunc (evt) { window.alert (evt.currentTarget.myParam); } <button class="input">显示参数</button>

JavaScript是一种面向原型的语言,记住!

someevar值应该只能在some_function()上下文中访问,而不能从侦听器的上下文中访问。 如果你想在监听器中拥有它,你必须这样做:

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

并使用newVar代替。

另一种方法是从some_function()返回someVar值,以便在监听器中进一步使用它(作为一个新的本地变量):

var someVar = some_function(someVar);