代码之家  ›  专栏  ›  技术社区  ›  Si8

为什么jQuery.done()不能识别外部函数

  •  0
  • Si8  · 技术社区  · 6 年前

    我有这样的想法:

      //works fine
      $.ajax("info.txt")
        .done(function(data) {
          console.log("works");
        })
    

    我还有这样的东西:

      //throws an error, stating CheckIt() inside the .done() is not a function
      $.ajax("info.txt")
        .done(function(data) {
          CheckIt(data);
        });
    
      function CheckIt(da) {
        console.log("it works");
      }
    

    为什么我会收到错误,以及如何绕过错误允许我使用其他函数。

    1 回复  |  直到 6 年前
        1
  •  1
  •   jrummell    6 年前

    很可能您的ajax请求失败了。如果将done替换为always,则即使请求失败,也将始终调用它。

    $.ajax("https://cat-fact.herokuapp.com/facts/random")
      .always(function(data) {
        CheckIt(data);
      });
    
    function CheckIt(da) {
      alert("it works");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>