将表单输入值设置为“”不清除空间
我正在尝试用 JavaScript 实现命令行模拟器。我希望空格键
键充当Enter
键(提交,然后清除命令行)。
在这篇文章中,让我们将 space
表示为下划线,因此 _
表示 [space]
:
如果我输入 banana_
> 然后,在捕获按键后,我调用 input.value= ""
,它会清除 banana
,但不会清除剩余的 space
。
我测试了 onkeydown
和 onkeypress
,但似乎没有任何区别。实际上, onkeyup
可以解决这个问题,请参阅下面我的答案!
这是我的代码。有人可以帮我删除多余的空间吗...
<html><head>
<script type="text/javascript">
document.onkeypress = keyCheck;
function keyCheck( e ) {
var keyID = (window.event) ? event.keyCode : ( e.keyCode ? e.keyCode : e.charCode );
switch(keyID) {
case 32: //spacebar
alert( "space pressed, clearing..." );
document.getElementById( "cli" ).value="";
break;
default:
//do something else
break;
}
}
</script>
</head>
<body>
<form name="frm" id="frm" onSubmit="go( this )">
<input name="cli" id="cli" type="text" name="cmd" size="122">
</body>
</html>
I am trying to implement a command line emulator in JavaScript. I want the Spacebar
key to act as Enter
(submit, then clear the command line).
In this post, let's represent a space
as an underscore, so _
means [space]
:
If I enter banana_
and then, after catching the keypress, I call input.value= ""
, it clears banana
, but not the remaining space
.
I tested both onkeydown
and onkeypress
, but it doesn't seem to make any difference. Actually, onkeyup
does the trick, see my answer below!
This is my code. Could someone please help me remove the extra space...
<html><head>
<script type="text/javascript">
document.onkeypress = keyCheck;
function keyCheck( e ) {
var keyID = (window.event) ? event.keyCode : ( e.keyCode ? e.keyCode : e.charCode );
switch(keyID) {
case 32: //spacebar
alert( "space pressed, clearing..." );
document.getElementById( "cli" ).value="";
break;
default:
//do something else
break;
}
}
</script>
</head>
<body>
<form name="frm" id="frm" onSubmit="go( this )">
<input name="cli" id="cli" type="text" name="cmd" size="122">
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请改用
onkeyup
。这样,事件发生在将字符添加到元素的值之后。
尝试一下: http://jsbin.com/esacu3
Use
onkeyup
instead.This way the event occurs after the character has been added to the value of the element.
Try it out: http://jsbin.com/esacu3