[英]Jquery blur function: Run second function after first. How?
I am trying to get a second function to run based on the results of the first. 我正在尝试根据第一个结果运行第二个函数。
$('#email').blur(function () {
id = $(this).attr('id');
$(myObj).data(id,"");
is_email(id); // If it's a valid email, it does this: $(myObj).data(id,"ok");
// Now if it's a valid email address, I want to run a second function to see if
// it's already taken.
if ($(myObj).data("email") == "ok") {
$(myObj).data("email",""); // Resets the value...
is_taken(id, "employees", "email"); // To test it again...
}
});
The first part works fine, but when I get to if($(myObj).... it is never checked. I'm assuming because this is set on the same blur event. I thought by putting it AFTER the first function, it would check the value of this object after the first function was complete. My guess is that it's checking if the value is "ok" before the first function has had a chance to return the value. 第一部分工作正常,但是当我进入if($(myObj)....时,它永远不会被检查。我假设是因为这是在同一模糊事件上设置的。我想通过将其放在第一个函数之后,它会在第一个函数完成后检查该对象的值,我猜是在第一个函数有机会返回该值之前检查它的值是否为“ ok”。
Because the functions use AJAX, the second is being invoked before the first AJAX call returns and sets the data value. 由于这些函数使用AJAX,因此在第一个AJAX调用返回并设置数据值之前,将调用第二个函数。 The key letter in AJAX is the first 'A' - asynchronous, meaning the code flow continues without waiting for the response.
AJAX中的关键字母是第一个'A'-异步,这意味着代码流将继续,而无需等待响应。 You can avoid this (and avoid using
data
to store the intermediate results) by changing your is_email
function to accept a callback. 您可以通过将
is_email
函数更改为接受回调来避免这种情况(并避免使用data
存储中间结果)。 Run the second function as the callback when the AJAX call completes depending on the result of the first call. 当AJAX调用完成时,根据第一个调用的结果,运行第二个函数作为回调。
function is_email( id, type, check, callback )
{
var that = this;
$.post( '/email/check', $('#'+id).val(), function(result) {
if (result == 'ok') {
if (callback) {
callback.call(that,id,type,check);
}
}
}
}
Used as: 用作:
is_email(id, "employees", "email", istaken);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.