【问题标题】:Input box that triggers function on keyword [closed]触发关键字功能的输入框[关闭]
【发布时间】:2021-08-16 17:22:57
【问题描述】:

如果我在这个输入框中输入“x”,我如何编写一个触发某个功能的输入框? (我正在使用 HTML 和 JavaScript)

这是我试过的代码:

<form>
<input type="text" placeholder="Type " id="inputId_1"></input>

<button type="button" onclick="getInputValue();">Get Value</button>
</form>

<script>
function getInputValue() {
      let an = document.getElementById(inputId_1).value;
    
     if (an == "k") {
    document.getElementById("iftest") = "zero was entered";
}
</script>
<p id ="iftest">Hello</p>

【问题讨论】:

  • an = 0 是一个赋值表达式,总是会产生true,例如你需要使用an == "x" 来进行比较。 (其中x 是您要查找的值)
  • @Peter Seliger,对不起,我不明白你的意思

标签: javascript inputbox


【解决方案1】:

对于这种特殊情况,您可以使用 keyupkeydown eventListeners:

function handleKeyUp(event) {
  if (event.key.toLowerCase() == "x") {
    console.log("x typed")
  }
}
&lt;input onkeyup="handleKeyUp(event)"&gt;

【讨论】:

    【解决方案2】:

    允许自定义匹配值的通用方法引入了一种可重用组件,该组件由其特定的custom data- 属性标识并通过querySelectorAll 和/或querySelector

    初始化过程是非常基本的,通过addEventListener向每个识别的输入元素添加一个通用实现的handler function来处理组件的事件。

    低级通用处理程序由任何input value change 触发,并从传递的event object 派生所有必要的数据。

    输入元素的value 和输入元素datasetmatch 值都将为toLowerCased,然后再尝试通过value.includes(match) 确定它们是否部分匹配。

    在这两种情况下,都将使用相关的 HTML output 元素,在前一种情况下,会呈现特定于错误的消息,而在后一种情况下会清除输出。

    function handleTextInputMatch(evt) {
      const elmInput = evt.currentTarget;
      const elmOutput = elmInput.parentNode.querySelector('output');
    
      const value = elmInput.value.toLowerCase();
      const match = elmInput.dataset.match.toLowerCase();
    
      if (value.includes(match)) {
    
        elmOutput.textContent = elmInput.dataset.matchOutput;
      } else {
        elmOutput.textContent = '';
      }
    }
    
    function initialize() {
      document
        .querySelectorAll('[data-text-input-match] [data-match]')
        .forEach(elmInput =>
          elmInput.addEventListener('input', handleTextInputMatch)
        );
    }
    
    initialize();
    output { color: #c00; }
    <form>
      <fieldset data-text-input-match>
        <legend>
          no "XXX" in any case
        </legend>
        <input
          type="text"
          data-match="xxx"
          data-match-output="partially invalid input value"
        />
        <output></output>
      </fieldset>
    
      <fieldset data-text-input-match>
        <legend>
          no "Foo" in any case
        </legend>
        <input
          type="text"
          data-match="FOO"
          data-match-output="invalid character sequence"
        />
        <output></output>
      </fieldset>
    </form>

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2023-03-15
      • 2019-11-12
      • 2018-01-19
      相关资源
      最近更新 更多