addEventListener 调用该函数,我什至没有要求它 [英] addEventListener calls the function without me even asking it to

查看:38
本文介绍了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.

这篇关于addEventListener 调用该函数,我什至没有要求它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆