addEventListener 调用该函数,我什至没有要求它

2022-01-29 00:00:00 javascript addeventlistener

所以我们有一个页面:

<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!

这是一个现场演示:http://jsfiddle.net/ey7pB/1/

推荐答案

引用 Ian 的答案:

由于第二个参数需要一个函数reference,因此您需要提供一个.使用有问题的代码,您会立即调用该函数并传递其 result (即 undefined...因为该函数所做的所有事情都是 alert 并且不返回任何内容).在匿名函数中调用函数(如您的第一个示例)或更改函数以返回函数.

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.

function message_me(m_text){
    alert(m_text)
} 

second.addEventListener('click', 
    function() {
        message_me('shazam');
    }
);

这是一个更新的 fiddle.

相关文章