-1

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

需要作为一行代码,例如:

javascript:oninputmyInput.pressKeynum1();

可以这样做吗?

4

2 回答 2

1

根据我发布的评论,这甚至jquery没有被标记

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

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

有了这个你手动触发keydown事件,这是enter事件

于 2013-02-18T15:48:02.493 回答
1

参考答案

如果您可以使用 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);
于 2013-02-18T15:50:40.863 回答