2016-10-19 78 views
2

我想从控制台使用纯JavaScript来触发按键事件,但无法这样做。下面纯JavaScript触发按键事件

是我的代码

var abc = document.querySelector("#main > footer > div.block-compose > div.input-container > div > div.input"); 

代码1:

function fire(elem, type) { 

    var evt = elem.createEvent("Events"); 

    evt.initEvent(type, true, true, window, 1); 

    elem.dispatchEvent(evt); 

} 

document.addEventListener("plop", function() { 
    console.log("Fired a synthetic click event"); 
}, false); 

fire(abc, "plop"); 

代码2

var event = document.createEvent("KeyboardEvent"); 

event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0); 

任何建议??

Jsfiddel链接:

http://jsfiddle.net/mishragaurav31/VLZGk/1105/

我只是希望能够警示 “的keyPressed”

+0

你是否看到任何错误? – Rajesh

+0

嘿,如果可能的话创建jsfiddle或者添加你的​​html代码也 –

+0

看看这个答案:http://stackoverflow.com/questions/22574431/testing-keydown-events-in-jasmine-with-specific-keycode/23700583 #23700583 – MarcoL

回答

-1

你是不是传递一个函数的按键绑定

尝试javascript代码:

$(document).ready(function() { 
     $("#txtInput").keypress(function(){ 
      alert("keypressed"); 
     }); 
}); 
+0

OP显然不使用jQuery,但是您的文章包含jQuery。这不会工作,除非他包含jQuery。 – Pachonk

+0

我刚刚提出了一个修复jsfiddle的问题。你是对的,标题说纯JavaScript,我的坏。 – crgarridos

-1

这个怎么样(用onkeydown调用发送密钥):jsBin

+1

请不要简单地链接到外部资源。演示你的答案是很好的,但总是想象你的答案有多好,如果你从你的答案中删除了所有非堆栈溢出链接。 – Pachonk