This question already has an answer here:
event listener in javascript not firing except for when the page is loaded
                            
                                (1个答案)
                            
                    
                5年前关闭。
        

    

因此,我尝试创建一个函数,该函数在调用时将事件侦听器添加到另一个div。奇怪的是,这是我第一次遇到此问题,因为我之前做过类似的事情...

无论如何,我已经隔离了问题,并编写了这个小脚本来显示问题:

<script>
function setNewClickEvent() {
    secondButton=document.getElementById('secondButton');
    secondButton.addEventListener('mouseup',outputHi());
}
function outputHi() {
    console.log('Hi');
}
</script>

<DIV id="firstButton" onclick="setNewClickEvent()" style="width:20px;height:20px;border:1px solid #000000;">
1
</DIV>

<DIV id="secondButton" style="width:20px;height:20px;border:1px solid #000000;">
2
</DIV>


我希望它的工作方式是单击firstButton时,它将addEventListener添加到secondButton中,这样,当secondButton按下时,它将运行功能outputHi()

但是,它不是执行此操作,而是在单击outputHi()时运行firstButton,甚至不将事件侦听器添加到secondButton

我错过了什么吗?

最佳答案

您要添加的侦听器是函数的输出,因为添加侦听器时正在执行它。您想要的是将函数本身添加为侦听器,而不是其输出。所以:

secondButton.addEventListener('mouseup', outputHi);


(注意该函数后缺少()

07-24 09:37
查看更多