【问题标题】:Javascript input run a function when specific text is typed in输入特定文本时,Javascript 输入会运行一个函数
【发布时间】: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


【解决方案1】:

两个问题:

  1. = 用于分配而不是相等检查 - 你想使用 ===
  2. 您将输入的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`);
  }
}

【讨论】:

  • 我想知道为什么一切看起来都正常但无法正常工作,谢谢您的回答,您是救生员。
猜你喜欢
  • 2013-10-16
  • 1970-01-01
  • 2019-01-17
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 2018-11-03
相关资源
最近更新 更多