jQuery不在第二功能内

时间:2018-10-16 02:47:50

标签: javascript jquery

我正在尝试在现有功能下调用新功能。第一个函数可以正常运行,但是代码不会放入test函数中。对这个问题有想法吗?

我遇到的错误是:未定义测试

var doIt;
var test;

$(document).ready(function() {
  test(2);
  doIt = function() { //now has global scope.
    test(1);
  };

  test = function(n) {
    alert('test function');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <input name="Go" type="button" value="Go" onclick="doIt();" />
</body>

1 个答案:

答案 0 :(得分:1)

您只需要在正确的位置定义事物即可。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
      var doIt;
      var test;

      $(document).ready(function()
      { 
         // You can't invoke test variable here since it has been declared
         // but not yet initialized.
         // test(2);
         // If you had declared a function instead, like the test2(),
         // then it would be in the scope of the whole document
         test2();

         doIt = function() {
          test(1);
         };

         test = function(n){
            alert('test function');
         };

         //you could invoke it here though, after it has been initialized 
         test(2);
      });
      function test2(){
         alert('test2 function');
      }
    </script>
  </head>
  <body>
    <input name="Go" type="button" value="Go" onclick="doIt();"/>
  </body>
</html>

请注意,您并未在任何地方声明函数。取而代之的是,您声明一个变量并在以后使用一个函数对其进行初始化,因此您必须尊重该变量的作用域