Definitive way to trigger keypress events with jQu

2018-12-31 04:16发布

I've read all the answers on to this questions and none of the solutions seem to work.

Also, I am getting the vibe that triggering keypress with special characters does not work at all. Can someone verify who has done this?

10条回答
余生无你
2楼-- · 2018-12-31 04:53

If you want to trigger the keypress or keydown event then all you have to do is:

var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
查看更多
浪荡孟婆
3楼-- · 2018-12-31 04:54

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    
查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 04:57

I made it work with keyup.

$("#id input").trigger('keyup');
查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 05:01

console.log( String.fromCharCode(event.charCode) );

no need to map character i guess.

查看更多
登录 后发表回答