【问题标题】:function called on click not defined单击时调用的函数未定义
【发布时间】:2015-07-15 10:52:02
【问题描述】:

单击按钮时不会调用函数。

<script>
    $(function() {

    var reset = function () {
    obj.x = canvas.width / 2;
    obj.y = canvas.height / 2;

    };
    });
  </script>
  <input type="button" onclick="reset();" />

为什么?

【问题讨论】:

  • 因为函数的scope不是global
  • 当然,您在 IIFE 中将该函数设为私有...
  • 为什么你的按钮在你的&lt;script&gt;里面?
  • @Tushar 但是如果我将此功能设为全局,我将看不到画布

标签: javascript jquery


【解决方案1】:

正如评论中已经说过的,您的 reset 函数位于本地范围内,这使得它在全局范围内不可见(您在其中设置了 onclick)。

这很好,真的,最好不要在全局范围内声明一堆函数。

这里的解决方案是正确附加事件处理程序:

  <script>
    $(function() {
          var reset = function () {
          obj.x = canvas.width / 2;
          obj.y = canvas.height / 2;
       }
       document.getElementById('myButton').addEventListener('click', reset);
    });
  </script>
  <input type="button" id=myButton/>

或者,你似乎在使用 jQuery:

  <script>
    $(function() {
          var reset = function () {
          obj.x = canvas.width / 2;
          obj.y = canvas.height / 2;
       }
       $('#myButton').click(reset);
    });
  </script>
  <input type="button" id=myButton/>

【讨论】:

    【解决方案2】:

    只需move reset declaration out of function,因为需要在全局范围内声明 javascript 处理程序。

    【讨论】:

    • 可能只有链接的答案。
    猜你喜欢
    • 2016-05-31
    • 2019-01-30
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多