为什么这个JS不能工作?这样做的目的是在文本框中输入一些不是帮助、windows-xp、显式、默认或无的内容,然后按enter键,并得到警告"Command is‘t exist“。
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>
发布于 2020-02-18 11:12:38
const validCommands = ["help", "windows-xp", "explicit", "default", ""];
if (!validCommands.includes(commandInput.value)) {
alert("Command doesn't exist.");
}发布于 2020-02-18 11:12:23
创建一个您想要允许的字符串数组(或集合),然后检查该数组是否.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>
还要注意,您应该尽可能避免使用内联处理程序,因为它们是have too many gotchas的,需要全局污染,并且是不好的做法-使用Javascript正确地附加事件侦听器,如上面的代码片段所示。
https://stackoverflow.com/questions/60273207
复制相似问题