Javascript 如何重构多个if-else语句

Javascript 如何重构多个if-else语句,javascript,jquery,Javascript,Jquery,我想在不使用这些多个if-else条件的情况下进行表单验证,我想使用单个if-else条件是否可行 根据您的示例,您可以将所有代码折叠为单个函数 例如: $("form").on("submit", function() { checkField("firstname", "dateofbirth", "Please enter date of birth."); checkField("lastname", "employeetypeid", "Please select em

我想在不使用这些多个if-else条件的情况下进行表单验证,我想使用单个if-else条件是否可行


根据您的示例,您可以将所有代码折叠为单个函数

例如:

$("form").on("submit", function() {
    checkField("firstname", "dateofbirth", "Please enter date of birth.");
    checkField("lastname", "employeetypeid", "Please select employee type.");
    checkField("username", "worklocationid", "Please select work location.");
    checkField("passwordConfirmation", "departmentid", "Please select organization/dept.");
});


function checkField(fieldToCheck, errorLabel, errorMessage ) {
    if ( $("#" + fieldToCheck).val() == "" ) {
        $("#" + errorLabel).html(errorMessage); 
    }
    else {
        $("#" + errorLabel).empty();
    }
}

根据您的示例,您可以将所有代码折叠为单个函数

例如:

$("form").on("submit", function() {
    checkField("firstname", "dateofbirth", "Please enter date of birth.");
    checkField("lastname", "employeetypeid", "Please select employee type.");
    checkField("username", "worklocationid", "Please select work location.");
    checkField("passwordConfirmation", "departmentid", "Please select organization/dept.");
});


function checkField(fieldToCheck, errorLabel, errorMessage ) {
    if ( $("#" + fieldToCheck).val() == "" ) {
        $("#" + errorLabel).html(errorMessage); 
    }
    else {
        $("#" + errorLabel).empty();
    }
}

我真的不知道语法,但是你能不能制作一个单独的方法,它包含一个字符串、一个目的地和一个可能的错误消息?大概是这样的:

function getValue(str, field, msg) {
    if($( str ).val() == "") {
        $( field ).html(msg);
    }
    else
    {
        $( field ).empty();
    }
}
然后用

getValue("#firstname", '#dateofbirth', "Please enter date of birth.") == "")
getValue("#lastname", '#employeetypeid', "Please select employee type.") == "")
getValue("#username", '#worklocationid', "Please select work location.") == "")
getValue("#passwordConfirmation", '#departmentid', "Please select organization/dept.") == "")

我真的不知道语法,但是你能不能制作一个单独的方法,它包含一个字符串、一个目的地和一个可能的错误消息?大概是这样的:

function getValue(str, field, msg) {
    if($( str ).val() == "") {
        $( field ).html(msg);
    }
    else
    {
        $( field ).empty();
    }
}
然后用

getValue("#firstname", '#dateofbirth', "Please enter date of birth.") == "")
getValue("#lastname", '#employeetypeid', "Please select employee type.") == "")
getValue("#username", '#worklocationid', "Please select work location.") == "")
getValue("#passwordConfirmation", '#departmentid', "Please select organization/dept.") == "")
这可能会帮助您我的建议正在使用,只需在每个输入中添加一个“必需”参数。这可能会帮助您我的建议正在使用,只需在每个输入中添加一个“必需”参数