JS触发keydown事件

我有点困惑为什么这段代码不起作用:

$(document).keydown(function(e){ if (e.keyCode == 39) { //RIGHT document.getElementById('col_detector_right').innerHTML=""; col_jack('right'); if(document.getElementById('col_detector_right').innerHTML!=""){ } else{ var left = document.getElementById('jack').style.left; var current_left = parseFloat(left); var new_left = current_left + 400; document.getElementById('jack').style.left = new_left+'px'; } right = true; return false; } if (e.keyCode == 37) { //LEFT document.getElementById('col_detector_right').innerHTML=""; col_jack('right'); if(document.getElementById('col_detector_right').innerHTML!=""){ } else{ var left = document.getElementById('jack').style.left; var current_left = parseFloat(left); var new_left = current_left - 4; document.getElementById('jack').style.left = new_left+'px'; } right = false; return false; } if (e.keyCode == 38) { //UP return false; } if (e.keyCode == 40) { //DOWN return false; } if (e.keyCode == 32) { //SPACE if(right==true){ var top = document.getElementById('jack').style.top; var current_top = parseFloat(top); var new_top = current_top -40; document.getElementById('jack').style.top = new_top+'px'; var left = document.getElementById('jack').style.left; var current_left = parseFloat(left); var new_left = current_left + 20; document.getElementById('jack').style.left = new_left+'px'; right=false; var press = $.Event('keydown'); press.which = 39; $(document).trigger(press); } else{ var top = document.getElementById('jack').style.top; var current_top = parseFloat(top); var new_top = current_top -40; document.getElementById('jack').style.top = new_top+'px'; } return false; } }); 

特别是这一点,不起作用:

 var press = $.Event('keydown'); press.which = 39; $(document).trigger(press); 

为什么? 这个想法是它应该触发右箭头键,但事实并非如此? 什么都没发生,它要么不触发它,要么没有正确检查keydown事件? 我不知道哪个或者是别的什么?

您需要将属性对象传递给jQuery Event对象,如下所示:

  // Create a new jQuery.Event object with specified event properties. var e = jQuery.Event("keydown", { keyCode: 64 }); // trigger an artificial keydown event with keyCode 64 jQuery("body").trigger( e ); 

阅读$ .Event的API文档 – http://api.jquery.com/category/events/event-object/