我是 JavaScript 新手,试图了解如何使用内置 addEventListener
方法。
当我通过 addEventListener
为特定事件调用匿名函数时,没有问题,一切正常。但是,当我为 mouseover
和 mouseout
事件调用外部函数时,我收到“Uncaught TypeError
”
A)工作示例(匿名函数):
myBtn.addEventListener("mouseover", function(){this.style.backgroundColor = 'yellow';} );
myBtn.addEventListener("mouseout", function(){this.style.backgroundColor = 'blue';} );
B)问题(外部函数):
myBtn.addEventListener("mouseover", changeBackground(this, 'yellow') );
myBtn.addEventListener("mouseout", changeBackground(this, 'blue') );
为了清楚起见,请查看以下内容:
完整演示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Dom Event Listener Example #02</h1>
<br>
<button type="button" id="myBtn1">Button 1</button><br>
<button type="button" id="myBtn2">Button 2</button><br>
<script>
"use strict";
var myBtn1 = document.getElementById("myBtn1");
var myBtn2 = document.getElementById("myBtn2");
//working scenario : anonymous function used
myBtn1.addEventListener("mouseover", function(){this.style.backgroundColor = 'yellow';} );
myBtn1.addEventListener("mouseout", function(){this.style.backgroundColor = 'blue';} );
// PROBLEM here, calling exteral function not working
myBtn2.addEventListener("mouseover", changeBackground(this, 'yellow') );
myBtn2.addEventListener("mouseout", changeBackground(this, 'blue') );
// external function, same functionality with anonymous function used above
function changeBackground(elem, col) {
elem.style.backgroundColor = col;
}
</script>
</body>
</html>
当您将鼠标悬停在按钮 1 上时,backgroundColor 参数将在黄色和蓝色之间切换,因此,mouseover
和 mouseout
对此工作正常。使用匿名函数向按钮 1 添加了事件。
虽然外部和匿名功能相同,但是当您将鼠标移入和移出时按钮 2,按钮 2 的 backgroundColor 没有变化,控制台输出以下错误;
Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
为什么调用匿名函数和外部函数的行为不同,即使它们的功能完全相同?我该如何修复它?
最佳答案
myBtn2.addEventListener("mouseover", changeBackground(this, 'yellow') );
您正在立即调用changeBackground(this, 'yellow')
并尝试使用其返回值作为事件监听器函数。
像之前一样将其包装在匿名函数中(或使用 the bind
method 生成函数)。
关于javascript - 未捕获的类型错误 : addEventListener not working when calling external function instead of anonymous function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34873657/