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

后端 未结 5 1909
逝去的感伤
逝去的感伤 2021-01-15 17:52

Here is my HTML/JavaScript:



        
相关标签:
5条回答
  • 2021-01-15 18:20

    You can not, it is private to that scope.

    0 讨论(0)
  • 2021-01-15 18:26

    You're placing the function's scope within another function, basically.

    Picture this:

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

    That is the facsimile of what you're trying to accomplish. Just like variables defined within a function are off limits outside of it, function names take on the same characteristics.

    Side-Note JavaScript doesn't require $ prefix on variable names (though is acceptable as far as names are concerned). I didn't know if you're coming from PHP and are just accustomed or were aware.

    Thought I'd make my comment an answer.

    0 讨论(0)
  • 2021-01-15 18:31

    Try this:

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

    Basically, you need to expose the function to global scope.

    0 讨论(0)
  • 2021-01-15 18:33

    What I ended up doing - what I should have done in the first place - is adding a click handler for the submit button:

    $("input[name='submitButton']").click(function(){...});
    
    0 讨论(0)
  • 2021-01-15 18:36

    Variables and methods declared inside the $(function() function are only accessible within that. If you need to use those outside, you you make it in the global namespace like

    window.functionName = functionName;
    
    0 讨论(0)
提交回复
热议问题