Javascript按输入类的键

时间:2013-02-18 15:36:20

标签: javascript

我正在尝试使用javascript按下我页面上的输入键。

需要像以下一行代码一样:

javascript:oninputmyInput.pressKeynum1();

可以这样做吗?

2 个答案:

答案 0 :(得分:1)

根据评论发布,即使jquery也未标记

// dummy event listener
$("input").keydown(function() { return true; });

var keyEvent = jQuery.Event("keydown");
keyEvent.keyCode = 13;
$("input").trigger(keyEvent);

用此手动触发keydown事件,这适用于enter事件

答案 1 :(得分:1)

Reference for Answers

如果你可以使用jQuery Workig JsFiddle

   // jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function(character) {
  // Internally calls jQuery.event.trigger
  // with arguments (Event, data, elem). That last arguments is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};

jQuery(document).ready( function($) {
  // Bind event handler
  $( 'body' ).keypress( function(e) {
    alert( String.fromCharCode( e.which ) );
    console.log(e);
  });
  // Simulate the key press
  $( 'body' ).simulateKeyPress('x');
});

适用于webkit和gecko的非jquery版本:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
                   "keydown", // event type : keydown, keyup, keypress
                    true, // bubbles
                    true, // cancelable
                    window, // viewArg: should be window
                    false, // ctrlKeyArg
                    false, // altKeyArg
                    false, // shiftKeyArg
                    false, // metaKeyArg
                    40, // keyCodeArg : unsigned long the virtual key code, else 0
                    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);