我对返回变量的状态有疑问。我有“altFormValidate”功能。本质上问题是,当我调用它时,如果蜜 jar 计数为 0,验证运行正常,并且“validationResult”变量返回 true,但如果蜜 jar 计数大于 0,“validationResult”变量仍然返回 false,即使在执行了应该使其成立的代码之后。
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;
}
}
所以我的问题是,为什么如果没有找到蜜 jar ,extraValidation() 返回 true,但如果找到蜜 jar ,则返回 false,但随后执行相关代码使其变为 true?我认为问题在于我返回 validResult 变量的位置。
最佳答案
我没有测试过,但我猜
if (!honeyPotCount > 0)
不等于
if (!(honeyPotCount > 0))
关于javascript - JS 函数返回 false 变量,而本应为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22095159/