javascript 如何从视图中捕获关键事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6033010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:13:19  来源:igfitidea点击:

how to capture the key event from a view ?

javascriptjavascript-eventsbackbone.js

提问by Running Turtle

I'm trying to capture the key event from a view as follows:

我正在尝试从视图中捕获关键事件,如下所示:

myView = Backbone.View.extend({

  el: $('#someDiv'),
  initialize: function(){
    // initialize some subviews
  },
  render: function(){
    return this;
  },
  events:{
   'keypress #someDiv': 'showKey'
  },
  showKey: function(e){
    console.log(e.keyCode);
  }
})

That does not work ?

那行不通?

ps: There a no [input] elements in the view or its subviews. I just need to know if the user presses any key and then do something on the view.

ps:视图或其子视图中没有 [input] 元素。我只需要知道用户是否按下任意键然后在视图上执行某些操作。

采纳答案by Julien

Key pressed goes to the focused element on the page. If you have nothing in your view and the view does not have any focus, then you will not have any key press events.

按下的键转到页面上的焦点元素。如果您的视图中没有任何内容并且视图没有任何焦点,那么您将不会有任何按键事件。

( btw if you want to do key press event for this.el, do "keypress" : "showKey" )

(顺便说一句,如果你想为 this.el 做按键事件,做 "keypress" : "showKey" )

In you above code the body will most likely receive all keypress events.

在上面的代码中,主体很可能会收到所有按键事件。

回答by Dan Caragea

You can do this in the view initialize() function:

您可以在视图 initialize() 函数中执行此操作:

_.bindAll(this, 'on_keypress');
$(document).bind('keypress', this.on_keypress);