2017-03-16 39 views
0

我已经成立,如果我要听上的所有文件,我应该做的事:如何使用JavaScript和流星模板来聆听按住所有文档的按键?

$(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() {}); ,但什么都没有发生过......

enter image description here

编辑:

如果我写的Web控制台它的工作原理验证码: enter image description here

那么,为什么它没有在我的流星模板代码工作?

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

第一个监听工作在窗口

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

回答

1

尝试(谁听tftextinput一)做相同的:

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

最后它作品,我只是把它放在其他地方谢谢你! – Jerome

+0

请记住,这段代码不会自动清除。所以如果你在'onRendered'回调函数中有这个,每次渲染模板时都会附加“keydown”事件监听器。假设你来回导航,并且模板被渲染5次,所以最终会有5个keydown处理程序附加到窗口对象。我主张使用模板级的助手,或者如果你真的需要将事件监听器附加到'window',然后在onDestroyed回调中进行清理:'Template.home.onDestroyed(function(){$(window).off (“keydown”)})' –

2

你可以使用模板事件

+0

我认为它会工作太btw – Jerome

+0

这是最好的流星答案。 – jordanwillis