为什么在调用document.ready()时未定义声明的函数

Why is a function declared in document.ready() not defined when called?

本文关键字:未定义 声明 函数 调用 document ready 为什么      更新时间:2023-09-26

这是我的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函数??

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

图片如下:

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

这是你努力实现的目标的翻版。就像函数中定义的变量在函数之外是禁止的一样,函数名称也具有相同的特性。

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

我想把我的评论作为一个答案

试试这个:

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

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

在$(function)函数中声明的变量和方法只能在其中访问。如果你需要在外部使用这些,你可以在像这样的全局命名空间中使用

window.functionName = functionName;

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

我最终要做的是为提交按钮添加一个点击处理程序:

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