簡體   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