我尝试从 javascript keydown 事件中挂钩一个字符
我想挂钩在输入文本字段中键入的字符,并在字段中键入“1”,以防按下“a”。
这是代码:
<html>
<body>
<script type="text/javascript">
function translate_code(charCode) {
switch (charCode) {
case 65: //
return '1' ;
case 97:
return '9';
}
}
function noEnglish(event) {
if (event.charCode) {
var charCode = event.charCode;
} else {
var charCode = event.keyCode;
}
if (65 <= charCode && charCode <= 90) {
document.getelementbyid("my_name").value += translate_code(charCode) ;
event.returnValue = false ;
}
}
</script>
<form>
<input type="text" name="my_name" id="my_name" onkeydown="noEnglish(event)" />
</form>
</body>
</html>
I would like to hook a character typed in an input text field and type '1' in the field in case 'a' was pressed.
Here is the code:
<html>
<body>
<script type="text/javascript">
function translate_code(charCode) {
switch (charCode) {
case 65: //
return '1' ;
case 97:
return '9';
}
}
function noEnglish(event) {
if (event.charCode) {
var charCode = event.charCode;
} else {
var charCode = event.keyCode;
}
if (65 <= charCode && charCode <= 90) {
document.getelementbyid("my_name").value += translate_code(charCode) ;
event.returnValue = false ;
}
}
</script>
<form>
<input type="text" name="my_name" id="my_name" onkeydown="noEnglish(event)" />
</form>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您无法通过
keydown
事件可靠地执行您想要的操作,该事件仅涉及按下的物理键,而不涉及与该键对应的字符。您需要的事件是keypress
。我之前在这里回答过类似的问题:
以下是满足您要求的实例:http://www.jsfiddle。网/timdown/NAC77/
First, you cannot reliably do what you want with the
keydown
event, which is concerned only with the physical key pressed and not the character corresponding with that key. The event you need iskeypress
.I've answered similar questions here before:
Here's a live example for your requirement: http://www.jsfiddle.net/timdown/NAC77/
首先,如果您想要“a”字符而不是“A”,则必须从 ASCII 字符 97 到 123 才能获取小写字母。您可能会希望它们全部如此 - 65 到 90 以及 97 到 123。
Well first of all, if you want the 'a' character and not 'A' you'll have to go from the ASCII character 97 until 123 to get the lower case letters. You'll probably want them all so - 65 until 90 and 97 until 123.