繁体   English   中英

如何使用JavaScript和Meteor模板收听在所有文档上按下的键?

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

我发现如果我想听所有文件,我应该这样做:

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

但是它在控制台中什么也没写...所以我尝试了其他这样的版本:

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

这段代码在$(document).ready(function() {}); 但是什么也没发生...

在此处输入图片说明

编辑:

如果我在Web控制台中编写此代码,则可以正常工作: 在此处输入图片说明

那么,为什么它在我的Meteor模板代码中不起作用?

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();
            }
        });
    });
});

第一个监听器起作用(监听tftextinput

您可以使用模板事件执行以下操作:

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

试一试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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