繁体   English   中英

按下Javascript后获取字符串值

[英]Get string value after key press in Javascript

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

澄清; 给定一个文本输入,我想看看如果用户按下某个键,我的文本输入将是什么值。

即,我想要以下功能。

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')

等等。 有一个简单的方法吗?

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

您可以通过处理每次输入字段发生更改时触发的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)"/> 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM