簡體   English   中英

兩次返回似乎不起作用

[英]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();
}

問題是其他函數都不總是返回有用的東西。

如果它們總是返回(並且理想情況下返回truefalse ),那么這將起作用。

也許

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();    
}

http://jsfiddle.net/LgepA/1/

&&是“和”。

在這種情況下,如果第一個函數返回 false,則第二個函數甚至不會被執行。 如果您希望 2nd 始終執行,您可以簡單地使用&

function completeFormValidation(){

    return !!(my_yearentry() & my_location());   
}

http://jsfiddle.net/LgepA/3/

或者以更易讀的方式:

function completeFormValidation(){

    var yearResult = my_yearentry();
    var locationResult = my_location();

    return yearResult && locationResult;   
}

http://jsfiddle.net/LgepA/4/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM