所以我想当用户在输入框中输入某个命令时运行一个函数。例如,当用户输入“我想要一个冰淇淋三明治”之类的内容时,它会运行一个函数,将 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 需要满足的条件。我已经花了几个小时寻找解决方案,我真的很惊讶我没有找到答案,因为这似乎是输入语句的主要功能。任何帮助将不胜感激,谢谢!
1 回答

弑天下
TA贡献1818条经验 获得超8个赞
两个问题:
=
用于赋值而不是相等检查 - 你想使用===
.您将
value
输入存储到 中readInput
,因此不需要value
从中引用:
function readCommand() {
let readInput = document.querySelector('#commandInput').value
// ↓ no .value, it's already here -----------↑
if (readInput === 'I want an ice cream sandwich') {
// ↑ === vs =
giveIceCreamSandwich()
} else {
alert(`Not a command`);
}
}
添加回答
举报
0/150
提交
取消