Jquery function is not working due to $(document).ready

前端 未结 4 446
花落未央
花落未央 2021-01-22 18:48

we have two js fie , test-1.js , test-2.js.




        
相关标签:
4条回答
  • 2021-01-22 18:57

    If you want to use code from test-1.js in test-2.js you have to load test-1.js first. JavaScript executes sequentially for synchronous code. So you can not access code from another scope (e.g. a file) if that code has not already been executed.

    0 讨论(0)
  • 2021-01-22 19:16

    Adding this second answer because you changed the order to be correct, but then also changed the contents of the scripts. Since they both contain a $(document).ready(function() {...}); where you create the functions, this means the functions you create only exist in the scope of that function, e.g.

    function foo() { 
      return 1;
    }
    
    $(document).ready(function() {
      // this is a new scope, functions created here will not be accessible outside of it.
      function bar() {
        return 2;
      }
    });
    
    foo(); // 1
    bar(); // Error: undefined is not a function
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-01-22 19:18

    Here you have two JavaScript files and you are using a function in test-2.js file which is present in test-1.js file.Your test_alert function is not working because you called that functin before the js file completely loaded,Due to the file loading delay your test_alert() is not working.

    Now ,you can use window.setTimeout() to solve this problem. Like:-

    $(document).ready(function (){
        function test_alert_2(){
            window.setTimeout(function(){
                test_alert();
                alert("helloo");   
            },1000);
    
        }
    
    });
    

    Through this code the test_alert() will be called after one second of script load. I thing this Will Help You.

    0 讨论(0)
  • 2021-01-22 19:21

    call test-1.js before test-2.js .

    Example

    <script type="text/javascript" src="test-1.js"></script>
    <script type="text/javascript" src="test-2.js"></script>
    
    0 讨论(0)
提交回复
热议问题