简体   繁体   中英

Why can’t I trigger this keydown event with jQuery?

I wanted to apply my JavaScript algorithm to solve 2048 game. http://gabrielecirulli.github.io/2048/

To do this first I wanted to add the possibility to simulate keydown events (left arrow, right, down, up) on the site with js

To do that I entered into the js console the following code:

var jq = document.createElement('script');
jq.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

Now I have jQuery on the site. Then I wanted to test if simulating keydown events works:

var e = $.Event("keydown", { keyCode: 39}); 
$("body").trigger(e);

But it seems that the event isn't invoked :(

What am I doing wrong ?

The 2048 page does not have nor use jQuery. From here you can see that "The .trigger() function cannot be used to mimic native browser events"

Also found at that site is another jQuery library, jquery.simulate.js, which allows for simulating native browser events.

You must remember that jQuery !== JavaScript. If the website does not use jQuery to begin with, adding it most likely will not produce a viable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM