首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建JS if语句来查看某个值是否不是某些字符串?

如何创建JS if语句来查看某个值是否不是某些字符串?
EN

Stack Overflow用户
提问于 2020-02-18 11:09:22
回答 2查看 50关注 0票数 1

为什么这个JS不能工作?这样做的目的是在文本框中输入一些不是帮助、windows-xp、显式、默认或无的内容,然后按enter键,并得到警告"Command is‘t exist“。

代码语言: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
复制
<form id="command-form">
  <input type="text" placeholder="Enter Command" id="command-input">
  <input type="submit" onclick="checkInput();" style="display: none;">
</form>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-18 11:12:38

使用Array.includes

代码语言:javascript
复制
const validCommands = ["help", "windows-xp", "explicit", "default", ""];

if (!validCommands.includes(commandInput.value)) {
  alert("Command doesn't exist.");
}
票数 2
EN

Stack Overflow用户

发布于 2020-02-18 11:12:23

创建一个您想要允许的字符串数组(或集合),然后检查该数组是否.includes了值:

代码语言:javascript
复制
function checkInput(event) {
  event.preventDefault();
  const commands = ["help", "windows-xp", "explicit", "default", ""];
  const { value } = document.getElementById("command-input");
  if (!commands.includes(value)) {
    console.log('Command doesnt exist ');
    return;
  }
  console.log('Carrying out command', value);
  commandForm.reset();
}
const commandForm = document.getElementById("command-form");
commandForm.addEventListener('submit', checkInput);
代码语言:javascript
复制
<form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit">
</form>

还要注意,您应该尽可能避免使用内联处理程序,因为它们是have too many gotchas的,需要全局污染,并且是不好的做法-使用Javascript正确地附加事件侦听器,如上面的代码片段所示。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60273207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档