【问题标题】:Failing adding function to addEventListener() [duplicate]未能将函数添加到 addEventListener() [重复]
【发布时间】:2017-04-21 14:53:55
【问题描述】:

我尝试添加事件监听功能,但由于某种原因它失败了。 见例子:

<!DOCTYPE html>
<html>
    <head>
        <script>    
        function loaded(){
                document.getElementById("first").addEventListener("click", showPopup());

        }


        function showPopup(){
            alert('hello');
        }


</script>
    </head>
    <body onload="loaded()">        
        <div id="first"> 
            click me !!!
        </div>
    </body>
</html>

点击“点击我!!!” text 什么都不做,而且 showPopup() 函数会触发一次。

对于这个微不足道的问题,我深表歉意,但我花了太多时间来发现错误。

非常感谢

【问题讨论】:

  • ("click", showPopup()) 应该只是 ("click", showPopup)。你想传递函数,而不是运行它。
  • 嗯...我删除了 showPopup() 上的括号,它运行良好... :-/

标签: javascript


【解决方案1】:

你不应该执行这个函数,而是传递它:

而不是这个:

document.getElementById("first").addEventListener("click", showPopup());

做:

document.getElementById("first").addEventListener("click", showPopup);

【讨论】:

    【解决方案2】:

    试试这个

    document.getElementById("first").addEventListener("click", showPopup);
    
    • showPopup 中删除了()

    `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2015-11-16
      • 2015-09-28
      • 1970-01-01
      • 2014-05-24
      • 2020-10-14
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多