简体   繁体   English

JavaScript addEventListener函数语法

[英]JavaScript addEventListener function syntax

I am having trouble understanding why the function parameter of the event listener isn't accepting just the function. 我无法理解为什么事件侦听器的功能参数不仅仅接受该功能。 Here's the code: 这是代码:

Variables are declared: 声明变量:

var spanJS = document.getElementById("spanJS")
var txtPlayers = document.getElementById("ContentPlaceHolder1_txtPlayers")
var txtAmount = document.getElementById("ContentPlaceHolder1_txtAmount")

Then associate the event listeners: 然后关联事件监听器:

txtAmount.addEventListener("keyup", UpdateTotals())
txtPlayers.addEventListener("keyup", UpdateTotals())

Then the function: 然后函数:

function UpdateTotals() {
      ... 
}

This is the whole code. 这是整个代码。 The problem is, when i run it, it executes UpdateTotals() without any keyup event, and the listeners don't work. 问题是,当我运行它时,它将执行UpdateTotals()而没有任何keyup事件,并且侦听器不起作用。

If i do the following change, it works like intended: 如果我进行以下更改,则将按预期工作:

txtAmount.addEventListener("keyup", function () {
UpdateTotals()
})
txtPlayers.addEventListener("keyup", function () {
UpdateTotals()
})

Can anyone explain me why i can't just put the function's name, i have to "child" it in another function? 谁能解释我为什么我不能仅仅把函数的名字放到另一个函数中?

In Javascript, UpdateTotals() is the value of the function when called without passing arguments, while UpdateTotals is the function itself 在Javascript中,UpdateTotals()是在不传递参数的情况下调用时函数的值,而UpdateTotals是函数本身

So you want: 所以你要:

txtAmount.addEventListener("keyup", UpdateTotals)
txtPlayers.addEventListener("keyup", UpdateTotals)

You need to change the event listeners by removing the () at the end of the handler names, like so: 您需要通过删除处理程序名称末尾的()来更改事件侦听器,如下所示:

txtAmount.addEventListener("keyup", UpdateTotals);

This is to pass the reference of the function UpdateTotals , and not run the function UpdateTotals() . 这是为了传递函数UpdateTotals引用 ,而不是运行函数UpdateTotals() The latter will actually run the function immediately, and pass in the return value of the function. 后者实际上将立即运行该函数,并传入该函数的返回值。

See this link about the idea of JavaScript function references (without parentheses). 有关JavaScript函数引用的想法,请参见此链接 (不带括号)。

You don't need the parentheses within the event listeners. 您不需要事件侦听器中的括号。

Change: 更改:

txtAmount.addEventListener("keyup", UpdateTotals())
txtPlayers.addEventListener("keyup", UpdateTotals())

to: 至:

txtAmount.addEventListener("keyup", UpdateTotals)
txtPlayers.addEventListener("keyup", UpdateTotals)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM