将 keydown 事件传递到另一个文本框
我正在尝试将 keydown
事件从一个文本框传递到另一个文本框。我的意思是,例如,如果您按“a”键,某些代码应该模拟该键在第二个文本框中被按下。
我不想只是将第一个文本框的值复制到第二个文本框 - 可以这么说,它应该基于每个键。假设第一个文本框包含 abc
,第二个文本框为空,那么当您在文本框 1 中按“d”键时,文本框 2 应该只包含 d
。
我已经尝试过的是(http://jsfiddle.net/E5qyr/1/):
$('#t1').keydown(function(e) {
$('#t2').keydown(e);
});
但是这个不起作用(我想我想得太简单了)。我知道我可以通过查看 e.keyCode 来附加按下的字符,但“退格键”等也必须起作用。
有人知道将 keydown
事件从一个文本框传递到另一个文本框吗?
I'm trying to pass an keydown
event from one textbox to another. What I mean with this is that if you, for example, press the 'a' key, some code should simulate that key as being pressed in the second textbox.
I do not want to just copy the value of the first textbox into the second - it should be on a per-key basis so to say. Suppose the first textbox contains abc
and the second textbox is empty, when you then press the 'd' key in textbox 1, textbox 2 should only contain d
.
What I already tried is (http://jsfiddle.net/E5qyr/1/):
$('#t1').keydown(function(e) {
$('#t2').keydown(e);
});
But this does not work (I guess I'm thinking too simple). I know I could append the character pressed by looking at e.keyCode
, but also 'backspace' etc. has to be working.
Does anybody have an idea to pass a keydown
event from one textbox to another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Textarea 元素没有自动安装侦听器,因此触发 #t2 的“keydown”事件不会显示响应。您想要的只是添加从 #t1 keydown 事件(您正在侦听)中获得的文本并将其附加到 #t2。
更新了对退格键的支持。找到其他代码 此处。
示例:
Textarea elements don't have listeners automatically installed to them, so triggering a 'keydown' event for the #t2 will not show a response. What you want is to just add the text you get from the #t1 keydown event (of which you are listening) and append it to your #t2.
UPDATED with support for backspace. Other codes found here.
Example:
为什么不替换 onkeydown 的文本框值?似乎只执行
txt1.text = txt2.text
而不是附加 txt1 中的现有字符串会更简单。Why not replace textbox value onkeydown? It seems it would be more simples to just do
txt1.text = txt2.text
instead of appending the existing strings in txt1.像这样的东西吗?
Something like this?