为什么此JS不起作用?目的是在文本框中输入无用的内容,windows-xp,显式,默认值或什么都不输入,然后按Enter键,并提示“命令不存在”。
<form id="command-form">
<input type="text" placeholder="Enter Command" id="command-input">
<input type="submit" onclick="checkInput();" style="display: none;">
</form>
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();
}
为要允许的字符串制作一个数组(或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>
Array.includes