简体   繁体   中英

How to listen the key pressed on all the document using JavaScript and Meteor template?

I have founded that if I want to listen on all the document I should do :

$(document).keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
});

but it doesn't write anything in the console... So I have tried an other version like this:

$(".container.body").keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
 });

this code is in the $(document).ready(function() {}); but nothing happened too...

在此处输入图片说明

EDIT:

If I write this code in the web console it works: 在此处输入图片说明

So why it doesn't work in my Meteor template code ?

Template.home.onRendered(function() {
    $(document).ready(function() {
        /*
        this method listen if we press "enter" in the research field and click on the button
        */
        $('#tftextinput').keypress(function(e) {
            if (e.keyCode == 13) {
                $('#tfbutton').click();
            }
        });
        $(document).keydown(function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
        });
    });
});

the first listener works (the one who listens tftextinput )

You could use Template events to do the same:

Template.home.events({
   'keydown':function(event){
       ...
   },
   'keypress #tftextinput': function(event){
       ...
   }
});

Try on window

$(window).on("keydown",function(e) {
          console.log(e);
          console.log(e.keyCode);
             if (e.keyCode == 27) {
               $('#tftextinput').value="";
               $('#tfbutton').click();
            }
 });

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