【问题标题】:I would like to turn this block of code into a keydown function that i could call from a html form我想把这段代码变成一个可以从 html 表单调用的 keydown 函数
【发布时间】:2021-11-29 08:08:12
【问题描述】:
  SetPoint :<input id="input" type="text" name="setPoint" onkeydown="return keyispressed(event);"    max="5" min="1" /><br /> 



 SetPoint :<input id="input" type="text" name="setPoint" onkeydown="return keyispressed(event);"    max="5" min="1" /><br /> 
    
    
    input.addEventListener("keydown", function(e){
        var charValue= String.fromCharCode(e.keyCode);
        if(((!/^(\d+)?([.]?\d{0,1})?$/.test(this.value + e.key)) && (e.which != 8 )))
        {
            e.preventDefault()
      }
    })

我希望设置点 html 输入表单调用 keydown 函数,然后运行以下代码,感谢提供的任何帮助

【问题讨论】:

    标签: javascript html forms function


    【解决方案1】:

    几件事:

    • 您的 HTML 无效,您有重复的 ids,应该是唯一的。

    • 您应该选择所有输入,循环遍历列表,并为每个输入添加事件侦听器

    document.querySelectorAll('input').forEach(input => {
      input.addEventListener("keydown", function(e) {
        var charValue = String.fromCharCode(e.keyCode);
        if (((!/^(\d+)?([.]?\d{0,1})?$/.test(this.value + e.key)) && (e.which != 8))) {
          e.preventDefault()
        }
      })
    })
    SetPoint :&lt;input type="text" name="setPoint" max="5" min="1" /&gt;&lt;br /&gt; SetPoint :&lt;input type="text" name="setPoint" max="5" min="1" /&gt;&lt;br /&gt;

    【讨论】:

    • 完美工作感谢@Spectric
    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2020-04-24
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多