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



为什么这个JS不起作用?目标是在文本框中输入一些没有帮助的内容,windows xp、显式、默认或什么都不输入,按enter键,并发出"命令不存在"的警告。

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

使用Array.includes:

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

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

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);
<form id="command-form">
<input type="text" placeholder="Enter Command" id="command-input">
<input type="submit">
</form>

还要注意的是,您应该尽可能避免使用内联处理程序,因为它们有太多的gotcha,需要全局污染,而且是不好的做法——而是使用Javascript正确地附加事件侦听器,就像上面的代码片段中一样。

最新更新