我遇到了返回變量狀態的問題。我有「altFormValidate」函數。本質上問題是,當我調用它時,如果蜜罐計數爲0,驗證運行良好,並且「validationResult」變量返回true,但是如果蜜罐計數大於0,則「validationResult」變量仍然返回false,即使在執行應該使其成爲真的代碼之後。JS函數返回應該爲true的虛假變量
function altFormValidate(intendedFormID){ //Validate honeypot traps
var validationResult = false;
}
var honeyPotFields = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"];
var honeyPotCount = 0;
honeyPotFields.forEach(function(entry) { //Check page for honeypots filled out
if($('#' + entry).length >= 1){
var honeyPotVal = $('#' + entry).val();
if (honeyPotVal !== ""){
honeyPotCount = honeyPotCount + 1; //Count successful honeypot traps
}
}
});
if (!honeyPotCount > 0) //Check honeypot count
{
$('#' + intendedFormID).attr("action", formAction); //Append SF action to form
validationResult = true;
}
else
{
if (honeyPotCount == 1){ //If one honeypot filled in
//SUSPECT - implement further checks
$.colorbox({ //init popup with confirmation input: "#machine-check"
href: "/inc/form-confirmation.html",
transition: "elastic",
speed: 350,
opacity: 0.65,
className: "seg-window",
onComplete: function() {
jQuery('#colorbox').find('a.btn-close, a.close, a.cancel').unbind('click.closeColorbox').bind('click.closeColorbox', function(e) {
jQuery.colorbox.close();
e.preventDefault();
});
jQuery('#machine-check').bind('change', function(e) {
jQuery.colorbox.close();
e.preventDefault();
validationResult = true; //This code doesn't seem to change the variable "validationResult" when I call the entire function altFormValidate but I know that changing "machine-check" does change the variable.
});
}
});
}
else if (honeyPotCount == 2){ //If two honeypots filled in
//PRIME SUSPECT - init Captcha/Akismet etc
alert("Robot Alert!");
validationResult = false;
}
} return validationResult;
}
,我致電上述功能,像這樣,在提交形式:
var req = true;
if(req){ //If required fields are filled in
var extraValidation = altFormValidate('WebToLeadForm', 'webToLeadPost');
if (extraValidation == true){
alert("form sent");
//document.WebToLeadForm.submit();
return true;
}
}
所以我的問題是,如果沒有蜜罐被發現爲什麼extraValidation()返回true,但假的,如果一個是發現但相關代碼然後執行,以使其成爲現實?我認爲這個問題是我返回validationResult變量的地方。
異步性是問題。在'altFormValidate'返回後''machine-check'的'change'處理器將會很長時間地被觸發。 – DCoder
啊,這很有道理!所以我怎麼才能使這個函數同步工作,因爲更改處理程序只會在altForm驗證函數之後觸發? – Barney
您無法將異步操作轉換爲同步操作,您應該做相反的操作。總是阻止實際的表單提交,給它'altFormValidate'一個它應該在知道最終值時調用的回調,並且在回調中AJAX提交表單值。查看異步工作流程的工作原理。 – DCoder