JavaScript addEventListener函数语法 [英] JavaScript addEventListener function syntax

查看:87
本文介绍了JavaScript addEventListener函数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么事件监听器的功能参数不仅仅接受该功能。代码如下:



声明变量:

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

然后关联事件侦听器:

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

然后该函数:

 函数UpdateTotals(){
...
}

这是完整的代码。问题是,当我运行它时,它将执行UpdateTotals()而没有任何键入事件,并且侦听器不起作用。



如果我进行以下更改,它将像预期的那样工作:

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

有人可以解释我为什么我不能只是把函数的名字放到另一个函数中吗?

解决方案

您需要通过删除处理程序名称末尾的()来更改事件侦听器,如下所示:

  txtAmount.addEventListener( keyup,UpdateTotals); 

这是为了传递函数 reference > UpdateTotals ,而不运行函数 UpdateTotals()。后者实际上将立即运行该函数,并传递该函数的返回值。



请参见此链接有关JavaScript函数引用的概念(不带括号)。 / p>

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.

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?

解决方案

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(). 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 addEventListener函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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