Javascript 输入在输入特定文本时运行一个函数

所以我想当用户在输入框中输入某个命令时运行一个函数。例如,当用户输入“我想要一个冰淇淋三明治”之类的内容时,它会运行一个函数,将 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 需要满足的条件。


我已经花了几个小时寻找解决方案,我真的很惊讶我没有找到答案,因为这似乎是输入语句的主要功能。任何帮助将不胜感激,谢谢!


SMILET
浏览 97回答 1
1回答

弑天下

两个问题:=用于赋值而不是相等检查 - 你想使用===.您将value输入存储到 中readInput,因此不需要value从中引用:function readCommand() {&nbsp; let readInput = document.querySelector('#commandInput').value&nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↓ no .value, it's already here -----------↑&nbsp; if (readInput === 'I want an ice cream sandwich') {&nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↑ === vs =&nbsp; &nbsp; giveIceCreamSandwich()&nbsp; } else {&nbsp; &nbsp; alert(`Not a command`);&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript