为什么在调用时没有定义document.ready()中声明的函数?

Eri*_*air 2 javascript methods jquery undefined

这是我的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>
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*tie 7

您基本上将函数的范围放在另一个函数中.

想象一下:

<script>
  document.onload = function(){
    function foo(){
      alert('bar');
    }
  };
  foo();
</script>
Run Code Online (Sandbox Code Playgroud)

这就是你想要完成的事情的传真.就像函数中定义的变量在其外部的限制一样,函数名称具有相同的特征.

Side-Note JavaScript在变量名称上不需要$前缀(尽管就名称而言是可接受的).我不知道你是来自PHP,只是习惯或意识到.

以为我会把我的评论作为答案.