简体   繁体   English

处理多个Javascript IF语句

[英]Dealing with multiple Javascript IF statements

Is it possible to put multiple IF statements in Javascript? 是否可以在Javascript中放入多个IF语句? If so, I'm having a fair amount of trouble with the statement below. 如果是这样,我在下面的声明中遇到了很多麻烦。 I was wondering if you can put another IF statement in between if (data == 'valid') AND else ? 我想知道是否可以在if(data =='valid')AND else之间插入另一个IF语句? I want to add another if data =='concept') between the two. 我想在两者之间添加另一个if data =='concept')

if (data == 'valid') {
    $("#file").slideUp(function () {
        $("#file").before('<div class="approvedMessage">WIN WIN WIN!</div>');
        setTimeout(ApprovedProof, 5000);
    });

    function ApprovedProof() {
        $("#file").slideDown();
        $('.approvedMessage').fadeOut();
    }

}
else {

    $("#file").slideUp(function () {
        $("#file").before('<div class="deniedMessage">NO NO NO!</div>');
        setTimeout(DeniedProof, 5000);
    });

    function DeniedProof() {
        $("#file").slideDown();
        $('.deniedMessage').fadeOut();
    }
}

is this what you're looking for? 这是您要找的东西吗?

if(data == 'valid') {
    // block 1
} else if (data == 'concept') {
    // block 2
} else {
    // block 3
}

If you intend for the data variable to hold many different values, you may find the switch statement a better fit for your needs: 如果您打算让数据变量保存许多不同的值,则可能会发现switch语句更适合您的需求:

switch(data)
{
  case "valid":
     //stuff
     break;
  case "concept":
     //stuff
     break;
  case "this": case "that":
     //more stuff
     break;
  default:
     break;
}

Note that break statements after each case, that multiple case statements can be used per condition, and that there is a catch-call default case that will fire if nothing else matched. 请注意,每种情况后都有break语句,每个条件可以使用多个case语句,并且如果没有其他条件匹配,则会触发catch调用默认情况。 The switch statement is nothing more than a more concise version of the If statement. switch语句不过是If语句的简洁版本。

you could use else if 你可以使用else if

if (data == "valid") {
    // stuff here
} else if (data == "concept") {
    // more stuff
} else {
    // other stuff
}

Unrelated to the question, but Joey asked for clarification of using an anonymous function with his timer: 与该问题无关,但乔伊要求澄清如何在计时器中使用匿名函数:

if (data == 'valid') {
    $("#file").slideUp(function () {
        $("#file").before('<div class="approvedMessage">WIN WIN WIN!</div>');
        setTimeout(function () {
            $("#file").slideDown();
            $('.approvedMessage').fadeOut();
        }, 5000);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM