javascript addEventListener 调用该函数,我什至不要求它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16310423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
addEventListener calls the function without me even asking it to
提问by LittleBobbyTables
So we have a page:
所以我们有一个页面:
<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>
And want to add some click events:
并想添加一些点击事件:
first.addEventListener('click', function(){alert('sup!');})
Works like a charm! However, when you make the second argument an external function:
奇迹般有效!但是,当您将第二个参数设为外部函数时:
function message_me(m_text){
alert(m_text)
}
second.addEventListener('click', message_me('shazam'))
It calls the function immediately. How can I stop this? So annoying!
它立即调用该函数。我怎么能阻止这个?很烦人!
Here's a live demo: http://jsfiddle.net/ey7pB/1/
这是一个现场演示:http: //jsfiddle.net/ey7pB/1/
回答by clav
Quoting Ian's answer:
引用伊恩的回答:
Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result(which is
undefined
...because all the function does isalert
and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.
由于第二个参数需要一个函数引用,因此您需要提供一个。使用有问题的代码,您会立即调用该函数并传递其结果(这是
undefined
...因为该函数所做的只是alert
并且不返回任何内容)。在匿名函数中调用该函数(如您的第一个示例)或更改该函数以返回一个函数。
function message_me(m_text){
alert(m_text)
}
second.addEventListener('click',
function() {
message_me('shazam');
}
);
Here's an updated fiddle.
这是一个更新的小提琴。
回答by Ian
Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result(which is undefined
...because all the function does is alert
and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.
由于第二个参数需要一个函数引用,因此您需要提供一个。使用有问题的代码,您会立即调用该函数并传递其结果(这是undefined
...因为该函数所做的只是alert
并且不返回任何内容)。在匿名函数中调用该函数(如您的第一个示例)或更改该函数以返回一个函数。
You can do this:
你可以这样做:
function message_me(m_text){
alert(m_text);
}
second.addEventListener('click', function () {
message_me('shazam')
});
or this:
或这个:
function message_me(m_text){
return function () {
alert(m_text);
};
}
second.addEventListener('click', message_me('shazam'));
回答by Sehyun Kim
or you can use .bind
或者你可以使用 .bind
function message_me(m_text){
alert(m_text);
}
second.addEventListener('click', message_me.bind(this, 'shazam'));
check MDN Documentationabout 'closures'
检查 有关“关闭”的MDN 文档
回答by Jesse Reza Khorasanee
Modern ES6 solution using arrow functions
使用箭头函数的现代 ES6 解决方案
second.addEventListener('click', () => message_me('shazam'))