我已經成立,如果我要聽上的所有文件,我應該做的事:如何使用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() {});
,但什麼都沒有發生過......
編輯:
那麼,爲什麼它沒有在我的流星模板代碼工作?
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();
}
});
最後它作品,我只是把它放在其他地方謝謝你! – Jerome
請記住,這段代碼不會自動清除。所以如果你在'onRendered'回調函數中有這個,每次渲染模板時都會附加「keydown」事件監聽器。假設你來回導航,並且模板被渲染5次,所以最終會有5個keydown處理程序附加到窗口對象。我主張使用模板級的助手,或者如果你真的需要將事件監聽器附加到'window',然後在onDestroyed回調中進行清理:'Template.home.onDestroyed(function(){$(window).off (「keydown」)})' –