【问题标题】:How to check users inputed string is in the array in javascript?如何检查用户输入的字符串是否在javascript的数组中?
【发布时间】:2020-10-26 07:58:08
【问题描述】:

我希望我的用户在 html 的输入框中键入一个字符串,而不是我想检查它是否在项目数组中。我正在使用这个 JS 代码:

var items = ["apple"];
var userInput = document.getElementById("input").value;

function lol() {
  document.write(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>

但是当我每次运行它时它都会给出false

【问题讨论】:

  • 欢迎您! document.getElementById("input") 是“实时”引用,document.getElementById("input").value 不是。从全局变量中删除.value,并将其添加到includesincludes(userInput.value)

标签: javascript html arrays input


【解决方案1】:

你需要移动

var userInput = document.getElementById("input").value;

进入函数,因为它在开始时分配值并且永远不会改变。

var items = ["apple"];

function lol() {
  var userInput = document.getElementById("input").value;
  console.log(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>

【讨论】:

    【解决方案2】:

    您可以为输入字段添加一个 onChange 事件侦听器,并为输入字段中的每次更改更改 userInput 值。

    var items = ["apple"];
    var userInput = document.getElementById("input").value;
    function onChangeUserInput (event) {
       console.log(event.target.value);
       userInput = event.target.value;
    }
    
    document.getElementById("input").addEventListener('change', onChangeUserInput);
    
    
    function lol() {
      document.write(items.includes(userInput));
    }
    <input type="text" id="input">
    <button onclick="lol()">check</button>

    【讨论】:

      【解决方案3】:

      我试图复制错误。这是我的代码 -

      var items = ['apple', 'orange', 'mango'];
      
      var input = 'apple';
      
      console.log(items.includes('apple'));
      

      它按预期工作。问题是您在按钮中调用了 lol() 函数。因此,该函数在页面加载时调用,而不是在单击时调用。另一件事是您必须将获取用户输入的行移到 lol() 函数中。

      【讨论】:

      • 查看我的评论,了解问题出在哪里。
      猜你喜欢
      • 2017-11-03
      • 2022-06-17
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多