Why can I not define functions in jQuery's doc

2019-01-02 18:15发布

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 :)

6条回答
大哥的爱人
2楼-- · 2019-01-02 18:24

They will come up as undefined if you put them in any scope that is not theirs. If you really want to use them outside of the scope of $(document).ready(...) then you need to declare them externally. Such as:

var foo;

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

foo(); // works now because it is in scope

Hope this helps.

查看更多
大哥的爱人
3楼-- · 2019-01-02 18:24

Just another addition:

When declaring functions or variables inside of the $(document).ready() function, these are inaccessible when using onclick() binds in the document.

You can either move your declarations outside of $(document).ready(), or you can use $('#element').on('click', function() {}) within `$(document).ready().

查看更多
只若初见
4楼-- · 2019-01-02 18:25
<script>
    $(document).ready(function(){
      myfnc = function (param1, param2)
      {
        alert('Hello');
      }
      myfnc();
    });
</script>
<input type="button" onclick="myfnc('arg1', 'arg2')" value="Click me">
查看更多
余欢
5楼-- · 2019-01-02 18:32

Your function is defined within the scope of the $(document).ready() callback and cannot be seen from the outside. Either define the function outside the $(document).ready() scope of call it only from within.

查看更多
只靠听说
6楼-- · 2019-01-02 18:33

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>

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.

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).

查看更多
看风景的人
7楼-- · 2019-01-02 18:48

You can but they must be called within the scope of the ready() method otherwise they lose scope when the ready() method exits.

For example, the code below will work:

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

  foo(); // still in the scope of the ready method
});
查看更多
登录 后发表回答