[英]Two returns doesn't seem to work
我有 html 在表单后运行 javascript,
form name="mortgage" method="post" action=" "onsubmit="return completeFormValidation();">
和用于验证的 javascript 代码,
主功能:
function completeFormValidation() {
return yearentry1();
return my_location();
} // End of completeFormValidation
主函数中的第一个函数:
function yearentry1(){
var yearval = document.mortgage.mortYear.value;
alert(yearval);
}
main 中的第二个函数:
function my_location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
}
返回两次似乎不起作用! 当第一个函数通过并返回 TRUE 时,函数退出并发送表单。
如果我可以让所有函数在 main 函数中运行,然后如果 main 中的任何函数返回 false,则返回 false 是否有可能?
“return”语句结束了函数,所以你不能在这之后调用任何东西。
错误的:
function completeFormValidation() {
return my_yearentry();
return my_location();
}
正确的:
function completeFormValidation() {
return my_yearentry() && my_location();
}
但是你的 my_yearentry 函数必须有一个布尔返回值。
这是行不通的,因为您的其他功能都没有准备好,但理想情况下您会想要执行以下操作:
function completeFormValidation() {
return my_yearentry() && my_location();
}
问题是其他函数都不总是返回有用的东西。
如果它们总是返回(并且理想情况下返回true
或false
),那么这将起作用。
也许
function yearentry1(){
var yearval = document.mortgage.mortYear.value;
return yearval;
}
和
function my_location(){
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
return true;
}
尽管将验证检查和验证报告混合在一起也可能有问题。 这可能是一个好的开始。
一旦函数返回,该函数调用就完成了。
function completeFormValidation() {
my_yearentry(); // take away return statement, just call the function
// you have inconsistent function name below :"yearentry1()"
return my_location();
}
大概,您只想在两个函数都返回 false 时提交表单。 在这种情况下,您需要以下内容:
function completeFormValidation() {
return my_yearentry() && my_location();
}
&&
是“和”。
在这种情况下,如果第一个函数返回 false,则第二个函数甚至不会被执行。 如果您希望 2nd 始终执行,您可以简单地使用&
:
function completeFormValidation(){
return !!(my_yearentry() & my_location());
}
或者以更易读的方式:
function completeFormValidation(){
var yearResult = my_yearentry();
var locationResult = my_location();
return yearResult && locationResult;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.