为什么我不能在jQuery的document.ready()中定义函数?

为什么我不能在jQuery的document.ready()中定义函数?

问题描述:

如果我将它们放在document.ready()函数中,函数将显示为undefined:

Functions come up as undefined if I place them in the document.ready() function:

$(document).ready(function(){
  function foo()
  {
    alert('Bar');
  }
});

foo(); // Undefined

为什么会发生这种情况?我确定我只是需要一些简单的理解:)

Why does this happen? I'm sure I'm just in need of some simple understanding :)

不确定为什么在中定义函数 ready()的范围对您很重要,但您可以通过预先声明 foo 来使其工作:

Not sure why defining the function with in the scope of ready() is important to you, but you can make it work by declaring foo up front:

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script>
var foo;                           // Here's the difference
$(document).ready(function(){
  foo = function ()
  {
    alert('Bar');
  }
});
</script></head><body>
<input type="button" onclick="foo()" value="Click me">
</body></html>

显然你不能打电话给 foo() ready()之后的内联脚本中,因为 ready()代码尚未运行,但是你可以稍后调用该函数。

Obviously you can't call foo() from the inline script immediately after ready() because the ready() code hasn't yet run, but you can call the function later on.

只需确保在 foo() code> ready()代码已运行(或初始声明 foo()无害函数。)

Just make sure that nothing can try to call foo() before the ready() code has run (or make the initial declaration of foo() a harmless function).