【发布时间】:2020-11-06 20:40:45
【问题描述】:
所以我想在用户在输入框中输入某个命令时运行一个函数。 例如,当用户键入“我想要冰淇淋三明治”之类的内容时,它会运行一个函数,将 1 个冰淇淋三明治添加到他们的库存中。但是,如果他们输入类似“Gerfabujohn”的内容,它会告诉您这不是命令。我已经完成了将三明治添加到库存中的功能,这不是问题。 这是我的js:
function readCommand() {
let readInput = document.querySelector('#commandInput').value
if (readInput.value = 'I want an ice cream sandwich') {
giveIceCreamSandwich()
} else {
alert(`Not a command`);
}
}
还有我的html:
<label for="commandFeild"> Enter Command: </label>
<input type="text" id="commandInput" name="commandFeild"><br><br>
<button class="triggerInput" onclick="readCommand()"> Run Command </button>
这里我尝试使用 querySelector 函数来使用它的 id 来查找输入框的值。到目前为止,这部分似乎有效。我使用 console.log 记录 readInput 的值,它从输入字段记录了正确的命令。 if 语句根本不起作用。显然,无论我输入什么,它都会返回 true 并运行该函数,而忽略了它为 true 需要满足的条件。
我一直在寻找解决方案几个小时,但我真的很惊讶我没有找到答案,因为这似乎首先是输入语句的主要功能。任何帮助将不胜感激,谢谢!
【问题讨论】:
-
单 = 表示“设定值”,双 == 表示“比较值”。所以这是您需要更改的内容:
readInput== 'I want an ice cream sandwich'同时删除value,因为您已经在引用它。 -
let readInput = document.querySelector('#commandInput').value您需要删除 .value,正如您在下面的 If 语句中调用的那样
标签: javascript html function input