为什么我不能在jQuery的document.ready()中定义函数? [英] Why can I not define functions in jQuery's document.ready()?

查看:98
本文介绍了为什么我不能在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).

这篇关于为什么我不能在jQuery的document.ready()中定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆