2013-02-18 69 views
-1

我正在嘗試在我的頁面上使用javascript按下輸入按鍵。Javascript輸入類上的按鍵

需要儘可能的像代碼一行:

javascript:oninputmyInput.pressKeynum1(); 

才能做到這一點?

+0

你的意思是要生成一個事件讓瀏覽器認爲一個鍵被按下? – 2013-02-18 15:37:17

+0

不,我想模擬一個按鍵 – Satch3000 2013-02-18 15:39:15

+0

現在我很困惑,因爲我沒有看到區別... – 2013-02-18 15:40:15

回答

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和壁虎工作的非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); 
1

基於評論我張貼這甚至jquery沒有標記

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

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

這個手動觸發​​事件,這是enter事件