Javascript 将密钥代码发送到 <textarea>元素

2022-01-15 00:00:00 event-handling jquery javascript keydown

我不知道如何在 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>

有什么想法可以实现吗?

Any ideas how could I achieve that?

推荐答案

事件被发送,浏览器只是没有反应(即在文本区域中放置字符)

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 );
})

这样就够了吗?

相关文章