将密钥代码发送到< textarea>元件 [英] Javascript sending key codes to a <textarea> element
问题描述
我无法弄清楚如何在textarea元素上触发keydown事件,例如想象我有两个textarea元素,当我在第一个键入的东西时,我想要第二个框显示打字,但是由于某种原因我必须通过事件来做。这是我尝试的,它不起作用:
I can't figure out how to trigger a keydown event on a textarea element, e.g. imagine i have two textarea elements and when i type something in the first one, I want the second box to show the typing as well, but for a certain reason I have to do it via events. This is what I tried and it doesn't work:
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<textarea id='first'></textarea>
<textarea id='second'></textarea>
<script>
jQuery("#first").keydown(function(event)
{
var keydown = jQuery.Event("keydown")
keydown.keyCode = event.keyCode
keydown.which = event.which
jQuery("#second").trigger(keydown)
})
</script>
任何想法如何实现?
推荐答案
事件发送,浏览器对此不起作用(即将文字放在textarea中)
The event is sent, the browser just doesn't react to it (i.e., put characters in the textarea)
并不是所有浏览器(我知道)允许您发送事件,而不仅仅是触发它们。但是即使这样做还远远不够完美
Not all browsers (that I know of) allow you to dispatch events, not just trigger them. But even doing that is far from perfect
// Gecko only
$("#first").keypress(function(event)
{
var evt = document.createEvent('KeyEvents');
evt.initKeyEvent(
event.type
, event.bubbles
, event.cancelable
, event.view
, event.ctrlKey
, event.altKey
, event.shiftKey
, event.metaKey
, event.keycode
, event.charCode
);
$('#second')[0].dispatchEvent( evt );
});
尝试这个例子,你会看到我的意思是远离完美。基本上,做你所要求的方式也是你不能 - 通过价值的方式。
Try this example and you'll see what I mean by how it's far from perfect. Basically, the way to do what you're asking is also the way you say you can't - by value.
但是,您可以传递自定义数据以及事件,这将导致一个解决方案看起来像这样
However, you can pass custom data along with the event, which leads to a solution that looks like this
$("#first").bind( 'keyup change', function(event)
{
$('#second').trigger( 'mimic', $(this).val() );
});
$("#second").bind( 'mimic', function( event, value )
{
$(this).val( value );
})
这样够好吗?
这篇关于将密钥代码发送到< textarea>元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!