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

Jam*_*ore 62 javascript jquery

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

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

foo(); // Undefined
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我确定我只是需要一些简单的理解:)

Ric*_*dle 68

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

<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>
Run Code Online (Sandbox Code Playgroud)

显然你不能foo()立即从内联脚本调用,ready()因为ready()代码还没有运行,但你可以稍后调用该函数.

只需确保foo()ready()代码运行之前没有任何东西可以尝试调用(或者进行foo()无害函数的初始声明).


Sov*_*iut 24

您可以但必须在ready()方法范围内调用它们,否则在ready()方法退出时会丢失范围.

例如,下面的代码将起作用:

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

  foo(); // still in the scope of the ready method
});
Run Code Online (Sandbox Code Playgroud)

  • 简单.在.ready(...)范围之外定义它们.我不明白你为什么如此依赖这样做.它可能为您带来什么好处? (8认同)

Nic*_*rdi 7

如果你将它们放在不属于它们的任何范围内,它们将会被定义为未定义.如果你真的想在$(document).ready(...)的范围之外使用它们,那么你需要在外部声明它们.如:

var foo;

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

foo(); // works now because it is in scope
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.