[英]jQuery wait till function finishes
I have this script: 我有这个脚本:
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);
}
});
I want to call 我想打电话
d = d.split(",");
Only after I'm sure d isn't undefined
. 只有在我确定d不是
undefined
。
How do I execute that after the $.get
functions finishes and d is assigned to the data? 在
$.get
函数完成并将d分配给数据之后,我该如何执行呢?
You could simply put it into the callback? 您可以简单地将其放入回调中? :
:
$.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);
}
});
Or using ES7 (very new stuff) : 或使用ES7(非常新的东西):
(async function(){
var d=await new Promise(function(r){
$.get("url",r);
});
d=d.split(",");
...
})();
You need to put the JS that depends on d being defined inside the get callback. 您需要将依赖于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);
}
});
});
jQuery.get() is asynchronous because it is a shorthand for jQuery.ajax() who's default option for requests is async: true . jQuery.get()是异步的,因为它是jQuery.ajax()的缩写,请求的默认选项是async:true 。
Read here about asynchronous requests. 在此处阅读有关异步请求的信息。
// 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);
}
});
});
You can only rely on d
to have a value in the block where it is assigned a value, which is inside the callback function(data){...}
. 您只能依靠
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);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.