Jquery 引导弹出框添加esc键按检查并关闭

Jquery 引导弹出框添加esc键按检查并关闭,jquery,closures,twitter-bootstrap,popover,Jquery,Closures,Twitter Bootstrap,Popover,我正在尝试扩展引导popover以关闭手动模式下的escape。我试图扩展popover类固有的tooltip类,如下所示: /* WHY CANT I CALL the HIDE FUNCTION WHEN ESC key press is intercepted???? Why is the hide class undefined when the keypress is intercetped? */ !function ($) { "use strict"

我正在尝试扩展引导popover以关闭手动模式下的escape。我试图扩展popover类固有的tooltip类,如下所示:

/* WHY CANT I CALL the HIDE FUNCTION WHEN ESC key press is intercepted????

   Why is the hide class undefined when the keypress is intercetped?
*/

!function ($) {

    "use strict"

    /* TOOLTIP PUBLIC CLASS DEFINITION
    * =============================== */

    var Tooltip = function (element, options) {
        this.init('tooltip', element, options)
    }

    Tooltip.prototype = {

        constructor: Tooltip

  , init: function (type, element, options) {
      //init logic here

      $(document).keypress(function (e) {
          if (e.which == 27) { this.hide };  
      });                    ^^^^^^^^^^^^^
                             this.hide is undefined on debug????
  }

  , hide: function () {
     //hide logic
  }
}
您需要使用以下选项:

$tooltip = this;
$(document).keydown(function(e){
   if (e.keyCode === 27)
      $tooltip.hide();
});
您的问题是,您想要的“this”实际上就是文档,它没有隐藏功能。当触发keypress/keydown事件时,函数中的“this”是触发事件的元素,因此文档。请记住,JavaScript具有函数作用域,这意味着您需要在许多不同函数中谨慎使用“this”变量。

您需要使用以下内容:

$tooltip = this;
$(document).keydown(function(e){
   if (e.keyCode === 27)
      $tooltip.hide();
});
您的问题是,您想要的“this”实际上就是文档,它没有隐藏功能。当触发keypress/keydown事件时,函数中的“this”是触发事件的元素,因此文档。请记住,JavaScript有函数作用域,这意味着在许多不同的函数中,您需要小心使用“this”变量