【问题标题】:JAVASCRIPT How to equal an if value for two or multiple values? [duplicate]JAVASCRIPT 如何使两个或多个值的 if 值相等? [复制]
【发布时间】:2019-08-07 15:07:22
【问题描述】:

我需要 javascript 方面的帮助。

例如,我有一个 x 值,我想在 if 语句中设置两个或多个等于 x 的值。

如果 x 等于苹果或梨或香蕉,它会写“水果”。我该怎么做?

我试过了||和 && 运算符。我试着把“,”和“;”值之间。

<form name="formname" action="send.php" method="post" onsubmit="return confirm();">

    Type your name : <input type="text" name="name"><br>

    <input type="submit" value="Send">
</form>

<script>
    function confirm() {
        var x = document.formname.name.value;
        if (x == "") {
            alert("You need to fill here!");
            return false;
        }

        else if (x == "Lisa" /* and a little more names... */) {
            alert("You can't enter here");
            return false;
        }
        else {
            alert("Welcome");
            return false;
        }
    }
</script>

当我在“else if”语句中的值之间加上“,”时,当我从“else if”语句中输入else name时,它会再次写入“You can't enter here”。但我除了它会写“欢迎”。

【问题讨论】:

  • 使用逻辑 OR (||),例如:else if (x == "Lisa" || x == "Other name" || ... )

标签: javascript if-statement


【解决方案1】:

function confirm() {
  var x = document.formname.name.value;
  if (x == "") {
    alert("You need to fill here!");
    return false;
  } else if (x == "Lisa" || x == "value2" || x == "value3") {
    alert("You can't enter here");
    return false;
  } else {
    alert("Welcome");
    return false;
  }
}
<form name="formname" action="send.php" method="post" onsubmit="return confirm();">

  Type your name : <input type="text" name="name"><br>

  <input type="submit" value="Send">
</form>

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2020-01-17
    • 2012-08-20
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    相关资源
    最近更新 更多