javascript - 未捕获的类型错误 : addEventListener not working when calling external function instead of anonymous function

标签 javascript dom-events typeerror addeventlistener anonymous-function

我是 JavaScript 新手,试图了解如何使用内置 addEventListener 方法。

当我通过 addEventListener 为特定事件调用匿名函数时,没有问题,一切正常。但是,当我为 mouseovermouseout 事件调用外部函数时,我收到“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 参数将在黄色和蓝色之间切换,因此,mouseovermouseout 对此工作正常。使用匿名函数向按钮 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/

相关文章:

javascript - 如何设置 iframe 高度以适合内容?

javascript - 将 png 转换为 Three.js 平面中的高度

javascript - 内联 JavaScript 代码是否会在文档加载事件之前执行?

django - python 2.7 上的错误 "__init__() got an unexpected keyword argument ' tcp_nodelay'"

python - 类型错误:需要一个可读的缓冲区对象

javascript - HTML 详情标签开启方向?如何改变?

javascript - 先执行JS,然后转到<a>上的'page.php

javascript - 更改 src 属性后图像不显示

javascript - ReactJS - 无法打印出待办事项,this.props.todos.map 不是函数

javascript - 客户端浏览器的 Socket.IO 检测有时会失败