如何在addEventListener中不带括号的情况下使用该函数? [英] How the function is used without parenthesis in addEventListener?

查看:85
本文介绍了如何在addEventListener中不带括号的情况下使用该函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何在 addEventListener('click',addItem)中调用此 addItem() removeItem()而不带括号.

I am not able to understand how this addItem() and removeItem() is called without parenthesis in addEventListener('click', addItem).

var addButton = document.getElementById('add');
addButton.addEventListener('click', addItem);

var removeButton = document.getElementById('remove');
removeButton.addEventListener('click', removeItem);

function addItem(){
    console.log('Add Button clicked');
}

function removeItem(){
    console.log('Remove Button clicked');
}

推荐答案

因为在这种情况下, addItem 被用作函数引用,而不是功能.

Because in this context, addItem is used as a function reference rather than the return value of the function.

如果您这样做:

addButton.addEventListener('click', addItem());

然后立即执行 addItem ,每当单击 addButton 时, addItem 的返回值(未定义).这将导致错误,因为 undefined 不是函数.

Then addItem would be executed straight away, and whenever addButton was clicked, the return value of addItem (which is undefined) would be called. This would result in an error, because undefined is not a function.

在这里,您是说,当我单击 addButton 时,查找我传递的函数引用,然后执行它.

Here, you're saying when I click addButton, lookup the function reference I passed, and execute it.

您也可以用两种不同的方式编写这种文字:

You can also write this two different ways:

addButton.addEventListener('click', "addItem()");
addButton.addEventListener('click', function() {
    addItem();
});

以上两种情况仍然会产生与原始代码相同的输出.

Both of the above will still result in the same output as your original code.

这篇关于如何在addEventListener中不带括号的情况下使用该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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