如何使用 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
)
试穿window
$(window).on("keydown",function(e) {
console.log(e);
console.log(e.keyCode);
if (e.keyCode == 27) {
$('#tftextinput').value="";
$('#tfbutton').click();
}
});
您可以使用模板事件来做同样的事情:
Template.home.events({
'keydown':function(event){
...
},
'keypress #tftextinput': function(event){
...
}
});
我发现如果我想听所有我应该做的文件:
$(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
)
试穿window
$(window).on("keydown",function(e) {
console.log(e);
console.log(e.keyCode);
if (e.keyCode == 27) {
$('#tftextinput').value="";
$('#tfbutton').click();
}
});
您可以使用模板事件来做同样的事情:
Template.home.events({
'keydown':function(event){
...
},
'keypress #tftextinput': function(event){
...
}
});