首页 > 解决方案 > 如何以正确的形式编写 if else 条件

问题描述

如何写简单if的取第一个表达式。下面的例子,我的代码看起来很像。我的意思是第一个条件email.val() 和第二个 条件!validateEmail(email.val())或表达式。我的大问题是如何检测执行第一个或第二个条件?

if(email.val() == "" || !validateEmail(email.val())){
    //call the condition again
    if(email.val() ==""){
        $("#error").html("<p>Email Cant be empty</p>");
        $("#error").show();
        setTimeout(function(){$("#error").fadeOut();}, 2000)
    }else{
        $("#error").html("<p>Wrong email format</p>");
        $("#error").show();
        setTimeout(function(){$("#error").fadeOut();}, 2000)
    }
    email.focus();
}

所以我不需要if再次调用它

if(email.val() == ""){
    $("#error").html("<p>Email Cant be empty</p>");
    $("#error").show();
    setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
    $("#error").html("<p>Wrong email format</p>");
    $("#error").show();
    setTimeout(function(){$("#error").fadeOut();}, 2000)
}

标签: javascript

解决方案


你大概有

if (condition1 || condition2) {
    if (condition1) {
         foo();
    } else {
         bar();
    }
    moo();
}

else只能在 和 时触发,condition1==false因此condition2==true您可以编写与

if (condition1) {
    foo();
    moo();
} else if (condition2) {
    bar();
    moo();
}

推荐阅读