【问题标题】:Why is a function declared in document.ready() not defined when called?为什么在 document.ready() 中声明的函数在调用时未定义?
【发布时间】:2011-05-25 19:09:55
【问题描述】:

这是我的 HTML/JavaScript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
    <script type="text/javascript" src="/script/jquery.js"></script>
    <script type="text/javascript">
        $(function(){
            var $str = "hello world";

            function foo() {
                alert($str);
            }
        });
    </script>
</head>
<body>
    <form name="statusUpdateForm" method="post">
        <input type="button" name="submitButton" value=" " onclick="foo();" />
    </form>
</body>
</html>

当我单击按钮时,我收到一个 JavaScript 错误,指出 foo 未定义。如何调用在 document.ready() 中声明的 JavaScript 函数?

【问题讨论】:

标签: javascript jquery methods undefined


【解决方案1】:

基本上,您将函数的作用域放在另一个函数中。

想象一下:

<script>
  document.onload = function(){
    function foo(){
      alert('bar');
    }
  };
  foo();
</script>

这就是你想要完成的事情的复制品。就像在函数中定义的变量在函数之外是禁区一样,函数名称具有相同的特征。

旁注 JavaScript 不需要在变量名称上加上 $ 前缀(尽管就名称而言是可以接受的)。我不知道你是从 PHP 来的,只是习惯了还是意识到了。

我想我会把我的评论作为答案。

【讨论】:

    【解决方案2】:

    试试这个:

    $(function() {
        window.foo = function () {
            alert('bar');
        }
    });
    

    基本上,您需要将函数公开到全局范围。

    【讨论】:

      【解决方案3】:

      在 $(function() 函数内声明的变量和方法只能在其中访问。如果您需要在外部使用它们,您可以在全局命名空间中进行,例如

      window.functionName = functionName;
      

      【讨论】:

        【解决方案4】:

        你不能,它是该范围私有的。

        【讨论】:

        • 也可以,只需要将函数复制到作用域外即可。如果你做这样的事情。这通常也是你想要的。虽然我建议在 ready-function 中使用$('input[type=button]').click(foo);
        • 我同意你的建议,但如果你考虑这个问题,我的回答仍然是正确的。您可以通过将全局范围变量指向它们来从私有范围内公开事物,但您仍然无法访问它们。这不是一个“抱歉帮不了你”的答案,而是为了教育范围规则。
        【解决方案5】:

        我最终做的——我首先应该做的——是为提交按钮添加一个点击处理程序:

        $("input[name='submitButton']").click(function(){...});
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-06
          • 1970-01-01
          • 2017-02-16
          • 1970-01-01
          • 1970-01-01
          • 2021-01-18
          • 1970-01-01
          相关资源
          最近更新 更多