代码之家  ›  专栏  ›  技术社区  ›  Ozgur Akcali

在Javascript中按键后获取字符串值

  •  0
  • Ozgur Akcali  · 技术社区  · 8 年前

    我想要的不是用javascript模拟按键事件,而是在按键后获取字符串的值。

    为了澄清;给定一个文本输入,我想看看如果用户按下某个键,我的文本输入的值是多少。

    i、 e,我想要下面的函数。

    function getStringValueAfterKeyPress(string, cursorPosition, keyCode) {
        // returns string value after key press with provided code on provided cursor position
    }
    
    getStringValueAfterKeyPress('test', 4, 8) // returns 'tes' (8 is keycode of backspace)
    getStringValueAfterKeyPress('test', 4, 37) // returns 'test' (37 is keycode of left arrow, hence string value has not changed)
    getStringValueAfterKeyPress('test', 4, 49) // returns 'test1' (49 is keycode of '1')
    

    等等。有简单的方法吗?

    P、 我的用例是在afterKeyDown事件上使用此方法,使用此方法在按此键后获取输入元素的值,如果它与某个正则表达式不匹配,则阻止此操作。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Reinstate Monica Cellio    8 年前

    通过处理 input 每次输入字段发生更改时触发的事件,包括按键、复制/粘贴、拖放等。。

    下面是一个验证不允许数字的名称输入字段的示例。。。

    // our validation function to stop numbers being entered
    function noNumbersAllowed() {
      this.value = this.value.replace(/\d/g, "");
    }
    
    // keep a reference to the element, so we don't have to search the DOM repeatedly
    var nameInput = document.getElementById("name");
    
    // create an input event listener that removes all numbers
    nameInput.addEventListener("input", noNumbersAllowed);
    
    // set focus because we're nice like that
    nameInput.focus();
    <input id="name" type="text" placeholder="Enter name (no numbers)"/>

    可以有多种类型的验证函数(如果需要的话),并将它们分配给需要验证的任何输入。