每个循环外的jQuery访问变量 [英] jQuery access variable outside each loop
问题描述
每个循环运行后,我需要访问var"cont".如果cont = true,我需要运行一封电子邮件,该电子邮件是在每个循环中的ajax调用后设置的. 我已经读过每个循环都是同步的,但是当我在每个循环之后控制台登录var cont时,即使设置为true,我也会得到false.
I need to access a var "cont" after each loop has run. I need to run an email if cont = true which is set after an ajax call in each loop. I've read that each loop is synchronous but when i console log var cont after each loop, i get false even though it is set as true.
$(".check").click(function (event) {
var cont = false;
event.preventDefault();
$("form.form").each(function (index) {
var $this = $(this);
var name = $this.find('input.name').val();
var company = $this.find('input.comp_name').val();
var jtitle = $this.find('input.job_title').val();
var link = $this.find('input.link').val();
var email = $('input.email').val();
if ((name === "") || (company === "") || (jtitle === "")) {
$this.addClass("NotFilled");
} else {
var url = $this.attr('action');
// fetch the data for the form
var data = $this.serializeArray();
$.ajax({
url: url,
data: data,
type: "post",
success: function (result) {
if (result === "success") {
cont = true;
$this.removeClass("NotFilled").addClass("filled");
//console.log(cont) I Get True here
} else {
cont = false;
$this.removeClass("filled").addClass("NotFilled");
}
return cont;
}
});
}
});
//console.log(cont) I Get false here
if (cont === "true") {
$.post("<?php bloginfo('template_url'); ?>/x/x.php", {
emailTo: email,
emailFrom: 'x@x.co.uk',
subject: 'New x x x',
message: 'We x x x'
},
function (data) {});
}
});
推荐答案
each
方法中的代码是ajax,本质上是异步的.
The code inside your each
method is ajax and it's async in nature.
所以声明
if(cont === "true"){
即使在ajax调用成功/失败之前,也将执行.
Will be executed even before the ajax calls succeeds/fails.
因此,您必须通过设置async标志将ajax转换为同步方式,或者将if
条件放入回调中.
So you must either convert the ajax to be sync by setting the async flag or put the if
condition inside the callback.
同步ajax调用示例:
Example synchronous ajax call:
$.ajax({
url: url,
data: data,
async: false
type: "post",
success: function (result) {
if (result === "success") {
cont = true;
$this.removeClass("NotFilled").addClass("filled");
//console.log(cont) I Get True here
} else {
cont = false;
$this.removeClass("filled").addClass("NotFilled");
}
return cont;
}
});
这篇关于每个循环外的jQuery访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!