jQuery等到函数完成

时间:2017-06-14 12:47:18

标签: javascript jquery asynchronous async-await wait

我有这个脚本:

var d;
$(".circle").click(function() {
    var id = $(this).attr('id');
    var MyDiv1 = document.getElementById(id);
    var name = MyDiv1.innerHTML;

    $.get("url", function(data){
    d=data;
    });

    d=d.split(",");
    var arrayLength = d.length;
    for (var i = 0; i < arrayLength; i++) {
        if(i==id)
         custom_alert(d[i], name);
    }
});

我想打电话

d = d.split(",");

只有在我确定d不是undefined之后 在$.get函数完成并将d分配给数据后,如何执行该操作?

4 个答案:

答案 0 :(得分:3)

你可以简单地把它放入回调中吗? :

    $.get("url", function(d){
         d=d.split(",");
         var arrayLength = d.length;
         for (var i = 0; i < arrayLength; i++) {
           if(i==id)
            custom_alert(d[i], name);
         }
    });

或使用ES7(非常新的东西):

(async function(){
var d=await new Promise(function(r){
  $.get("url",r);
});
d=d.split(",");
...
})();

答案 1 :(得分:2)

你需要把依赖于d的JS放在get回调中。

var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;

$.get("url", function(data){
d=data;

   d=d.split(",");
   var arrayLength = d.length;
   for (var i = 0; i < arrayLength; i++) {
    if(i==id)
     custom_alert(d[i], name);
   }
 });
});

答案 2 :(得分:2)

jQuery.get()是异步的,因为它是jQuery.ajax()的简写,对于请求的默认选项是 async:true

Read here关于异步请求。

// declare it here if you need its values later (to be a global variable), or move it inside function(){ } declared inside $.get() call.
var d;
$(".circle").click(function() {
    var id = $(this).attr('id');
    var MyDiv1 = document.getElementById(id);
    var name = MyDiv1.innerHTML;

    $.get("url", function(data){
         d=data;
         // $.get has an asynchronous answer (you don't know when it will come or if it comes). Call d.split here
         d=d.split(",");
         var arrayLength = d.length;
         for (var i = 0; i < arrayLength; i++) {
             if(i==id)
              custom_alert(d[i], name);
        }
    }); 
 });

答案 3 :(得分:1)

您只能依靠d在块中为其分配值的值,该值位于回调function(data){...}内。

var d;
$(".circle").click(function() {
  var id = $(this).attr('id');
  var MyDiv1 = document.getElementById(id);
  var name = MyDiv1.innerHTML;

  $.get("url", function(data){
    d=data.split(",");
    var arrayLength = d.length;
    for (var i = 0; i < arrayLength; i++) {
      if (i==id)
        custom_alert(d[i], name);
    }
  });
});