我如何制作JS if语句以查看值是否不是某些字符串?

问题描述 投票:0回答:2

为什么此JS不起作用?目的是在文本框中输入无用的内容,windows-xp,显式,默认值或什么都不输入,然后按Enter键,并提示“命令不存在”。

HTML

<form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit" onclick="checkInput();" style="display: none;">
</form>

JavaScript

function checkInput() {
    var commandInput = document.getElementById("command-input")

    if ( commandInput.value !== "help", "windows-xp", "explicit", "default", "" ) {
        alert("Command doesn't exist.");
    }

    event.preventDefault();

    document.getElementById("command-form").reset();
}
javascript html
2个回答
0
投票

为要允许的字符串制作一个数组(或Set),然后检查数组.includes是否为值:

function checkInput() {
  const commands = ["help", "windows-xp", "explicit", "default", ""];
  const { value } = document.getElementById("command-input");
  if (!commands.includes(value)) {
    console.log('Command doesnt exist ');
  }
  event.preventDefault();
  document.getElementById("command-form").reset();
}
<form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit" onclick="checkInput();">
</form>

0
投票

使用Array.includes

Array.includes
© www.soinside.com 2019 - 2024. All rights reserved.